Python Unit 2
Python Unit 2
Let’s look at Radio Buttons and Check Buttons (Checkboxes) in Python GUI
programming—especially with tkinter, which is the standard GUI library.
1️.Radio Buttons
Radio buttons let the user select ONE option from a set.
In tkinter:
Use tk.Radiobutton.
All radio buttons in the same group are linked by a common variable (like
tk.StringVar() or tk.IntVar()).
import tkinter as tk
root = tk.Tk()
choice = tk.StringVar()
root.mainloop()
2️.Check Buttons (Checkboxes)
In tkinter:
Use tk.Checkbutton.
import tkinter as tk
root = tk.Tk()
var1 = tk.IntVar()
var2 = tk.IntVar()
var3 = tk.IntVar()
root.mainloop()
Main differences:
Feature Radio Button Check Button
Linked variable Shared (same variable for all buttons). Each has its own variable.
What is Canvas?
A canvas is a special widget where you can draw graphics, shapes, or images.
It’s like a blank space for making custom drawings (lines, rectangles, circles, etc.).
import tkinter as tk
root = tk.Tk()
root.title("Canvas Example")
# Create a canvas
canvas.pack()
# Draw shapes
root.mainloop()
EXPLANATION
import tkinter as tk
➡️This imports the tkinter library and gives it a short name: tk. You use this to create the
GUI.
root = tk.Tk()
root.title("Canvas Example")
➡️This creates the main window (often called the "root window").
# Create a canvas
canvas.pack()
width=300, height=200 sets its size (300 pixels wide, 200 pixels tall).
# Draw shapes
The oval fits inside the rectangle from (50, 120) to (150, 180).
root.mainloop()
Keeps the window open, waiting for any user action (like closing it).
A menu is a list of options or commands at the top of the window (like File, Edit,
etc.).
import tkinter as tk
def new_file():
def open_file():
print("File Opened!")
def exit_app():
root.destroy()
root = tk.Tk()
root.title("Menu Example")
menu_bar = tk.Menu(root)
file_menu.add_command(label="New", command=new_file)
file_menu.add_command(label="Open", command=open_file)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=exit_app)
menu_bar.add_cascade(label="File", menu=file_menu)
root.config(menu=menu_bar)
root.mainloop()
EXPLANATION
import tkinter as tk
➡️This imports the tkinter library, which you use to build the GUI.
def new_file():
def open_file():
print("File Opened!")
def exit_app():
root.destroy()
root = tk.Tk()
root.title("Menu Example")
➡️This creates the main GUI window and sets its title bar to "Menu Example."
Set up the menu bar:
menu_bar = tk.Menu(root)
➡️You create a menu bar object that will hold all your menus (like "File", "Edit", etc.).
➡️You create a File menu (the dropdown that appears when you click "File").
tearoff=0: Disables the dotted line at the top of the menu (prevents it from being
detachable).
file_menu.add_command(label="New", command=new_file)
file_menu.add_command(label="Open", command=open_file)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=exit_app)
menu_bar.add_cascade(label="File", menu=file_menu)
➡️This adds the File menu (the dropdown) to the menu bar, with the label "File."
root.config(menu=menu_bar)
➡️This tells the window to display the menu bar you just created.
root.mainloop()
➡️Starts the GUI event loop, keeping the window open and waiting for actions (like clicking a
menu item).
The image you provided lists popular Python libraries used in data science and scientific
computing:
pandas: For data manipulation and analysis (works well with tables/dataframes).
SciPy: For scientific computing (builds on NumPy with advanced math, stats,
optimization, etc.).
1️.NumPy
What it is:
✅ Key feature:
import numpy as np
Output:
[ 2 4 6 8 10]
2️.pandas
What it is:
Especially good for working with tabular data (like Excel sheets).
✅ Key feature:
import pandas as pd
# Create a DataFrame
df = pd.DataFrame(data)
print(df)
Output:
markdown
Name Age
0 Alice 25
1 Bob 30
3️.matplotlib
What it is:
✅ Key feature:
# Data
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
# Plot
plt.plot(x, y)
plt.show()
4️.SciPy
What it is:
✅ Key feature:
def f(x):
return x ** 2
# Integrate from 0 to 1
print(result)
Output:
0.33333333333333337
In summary:
Library Main Use Key Object / Feature
SciPy Advanced scientific computing (math, stats, etc.) Integrate, optimize, etc.
o (1, 2)
o (2, 4)
o (3, 6)
o (4, 8)
The result is a simple line plot showing a straight, upward-sloping line, because y increases
in direct proportion to x (y = 2x).
Great question! Let’s go through the NumPy installation process step by step, along with a
simple explanation.
What happens:
It installs NumPy and all its required files so you can import and use it in your Python
programs.
After installation, you can test if NumPy is working by opening a Python shell and typing:
import numpy as np
print(np.__version__)
This will print the version of NumPy you have installed (e.g., 1.25.0).
This is especially useful because Anaconda handles all dependencies and is often better for
scientific computing.
o Make sure Python and pip are added to your system’s PATH.
o NumPy supports Python 3.x; older Python versions may have compatibility
issues.
Virtual environments:
o It’s a good idea to create a virtual environment and install NumPy inside it to
avoid conflicts between projects.
Why install NumPy?
NumPy is not included by default with Python. You need to install it manually to:
What is ndarray?
It allows for fast, efficient mathematical and logical operations on large datasets.
import numpy as np
You can convert a regular Python list (or a list of lists) into an ndarray:
print(arr1)
Output:
[1 2 3 4]
This is a 1D array.
2️.Creating a 2D array
print(arr2)
Output:
[[1 2 3]
[4 5 6]]
3️.Creating a 3D array
print(arr3)
a) Zeros array
print(zeros_arr)
b) Ones array
print(ones_arr)
print(range_arr)
Output: [1 3 5 7 9]
d) Identity matrix
identity_arr = np.eye(3)
print(identity_arr)
print(arr2.shape) # (2, 3)
print(arr2.ndim) # 2
In summary:
✅ Conclusion:
The ndarray is central to NumPy, and you can create it from lists or using built-in functions
like zeros(), ones(), and arange(). This allows efficient handling of large data and complex
mathematical operations.
import numpy as np
print(arr3)
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
Explanation:
This is a 3D array:
import numpy as np
print(zeros_arr)
[[0. 0. 0.]
[0. 0. 0.]]
Explanation:
The numbers are shown as 0. (with a decimal point) because NumPy defaults to float
type unless specified otherwise.
import numpy as np
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
Explanation:
This creates a 3×3 array (like a square matrix) filled with 1.0.
NumPy allows element-wise arithmetic operations between arrays (of the same shape) or
between an array and a single number (scalar).
This is much faster and easier than using loops in regular Python.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
1️.Addition
result = a + b
print(result)
Output:
[5 7 9]
2️.Subtraction
result = a - b
print(result)
Output:
[-3 -3 -3]
3️.Multiplication
result = a * b
print(result)
Output:
[ 4 10 18]
4️.Division
result = a / b
print(result)
Output:
Example:
result = a * 10
print(result)
Output:
[10 20 30]
Square root:
print(np.sqrt(a))
Exponentiation:
print(a ** 2)
Sine:
print(np.sin(a))
Broadcasting
Example:
print(result)
Output:
[[2 2 4]
[5 5 7]]
In Summary:
Indexing and slicing are techniques used to access elements or subsets of elements from
sequences like lists, strings, or tuples in Python.
Indexing
Indexing means accessing an individual element from a sequence using its position (index).
Python uses zero-based indexing (i.e., the first element is at index 0).
You can also use negative indexing to count from the end (-1 is the last item).
text = "Hello"
Slicing
sequence[start:stop:step]
Boolean indexing is a powerful technique in Python (especially with NumPy and Pandas)
that allows you to select elements from a sequence (like a list, NumPy array, or DataFrame)
based on True/False conditions.
Basic Concept:
You create a boolean list or array where each True value indicates the element to keep, and
False indicates the element to ignore.
⚠️Plain Python lists don't support direct boolean indexing like NumPy arrays do, so you
need a loop or list comprehension as above.
import numpy as np
import pandas as pd
df = pd.DataFrame({
})
print(adults)
Output:
name age
0 Alice 25
2 Charlie 30
Summary:
import numpy as np
[4, 5, 6]])
transposed = arr.T
print(transposed)
Output:
[[1 4]
[2 5]
[3 6]]
np.transpose(arr)
Swapping Axes
Swapping axes means exchanging any two dimensions (axes) in a multi-dimensional array
(not just rows/columns).
Let's walk through your code and explain the result step by step.
🔸 Original Array (arr)
arr = np.array([
[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]
])
2 blocks (axis 0)
Think of it like:
[3, 4]]
[7, 8]]
swapped = np.swapaxes(arr, 0, 2)
This swaps:
So, shape changes from (2, 2, 2) to (2, 2, 2) — shape is the same, but structure is
reorganized.
🔸 Output:
print(swapped.shape)
Output:
(2, 2, 2)
print(swapped)
Output:
[[[1 5]
[3 7]]
[[2 6]
[4 8]]]
What Happened?
Each element at position [i, j, k] in the original array is moved to [k, j, i] in the new array.
Here's a mapping:
[0, 0, 0] 1 [0, 0, 0]
[0, 0, 1] 2 [1, 0, 0]
[0, 1, 0] 3 [0, 1, 0]
[0, 1, 1] 4 [1, 1, 0]
[1, 0, 0] 5 [0, 0, 1]
[1, 0, 1] 6 [1, 0, 1]
[1, 1, 0] 7 [0, 1, 1]
[1, 1, 1] 8 [1, 1, 1]
🔸 Why “Pseudo”?
Because the numbers only appear random, but are actually calculated using a formula and a
starting point called a seed.
If you use the same seed, you get the same sequence of numbers every time.
🔸 How It Works:
4. Repeat.
import random
random.seed(42)
82
0.6394267984578837
import numpy as np
np.random.seed(0)
# Generate random integers
🔹 Real vs Pseudorandom
Deterministic Yes No
🔸 Summary:
Fast and good enough for most tasks (e.g., games, simulations)
In Python, Universal Functions (ufuncs) are functions that operate on NumPy arrays
element-wise. They are a core part of NumPy and are optimized for fast computation on
large arrays, usually in a vectorized way (without the need for explicit loops).
ufuncs are functions that perform operations on arrays or other iterable objects,
element by element.
These functions broadcast (apply to arrays of different shapes) and can handle scalar
values as well (like 5 or 2.3).
They are written in C and thus execute faster than a regular Python loop over arrays.
1. Arithmetic Functions:
These functions perform element-wise arithmetic operations like addition,
subtraction, etc.
2. import numpy as np
3.
4. # Example array
6.
12.
18.
22.
You can apply ufuncs to both arrays and scalars. If the operands are scalars (like a single
number), the function will still work as expected.
print(result) # Output: [2 4 6 8]
You can also define your own ufuncs in NumPy using np.frompyfunc() or by creating an
operation with vectorize.
def custom_function(x):
ufunc = np.frompyfunc(custom_function, 1, 1)
result = ufunc(arr)
They include built-in functions for mathematical, logical, and bitwise operations.
They are designed to perform operations in a vectorized way, which is much faster
than using Python loops.