[go: up one dir, main page]

0% found this document useful (0 votes)
3 views29 pages

Python Unit 2

The document provides an overview of Radio Buttons and Check Buttons in Python's tkinter GUI, explaining their functionality and differences. It also introduces the Canvas widget for drawing graphics and discusses creating menus in tkinter. Additionally, it covers popular Python libraries for data science, including NumPy, pandas, matplotlib, and SciPy, along with their installation process and key features.

Uploaded by

raafiask
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views29 pages

Python Unit 2

The document provides an overview of Radio Buttons and Check Buttons in Python's tkinter GUI, explaining their functionality and differences. It also introduces the Canvas widget for drawing graphics and discusses creating menus in tkinter. Additionally, it covers popular Python libraries for data science, including NumPy, pandas, matplotlib, and SciPy, along with their installation process and key features.

Uploaded by

raafiask
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Great topic!

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

What are they?

 Radio buttons let the user select ONE option from a set.

 Example: Choose a gender:


(o) Male
( ) Female
( ) Other

In tkinter:

 Use tk.Radiobutton.

 All radio buttons in the same group are linked by a common variable (like
tk.StringVar() or tk.IntVar()).

Example: Radio Buttons

import tkinter as tk

root = tk.Tk()

root.title("Radio Button Example")

# Variable to hold the selection

choice = tk.StringVar()

# Create radio buttons

tk.Radiobutton(root, text="Option 1", variable=choice, value="1").pack()

tk.Radiobutton(root, text="Option 2", variable=choice, value="2").pack()

tk.Radiobutton(root, text="Option 3", variable=choice, value="3").pack()

root.mainloop()
2️.Check Buttons (Checkboxes)

What are they?

 Check buttons let the user select MULTIPLE options.

 Example: Pick your hobbies:


[x] Reading
[ ] Swimming
[x] Gaming

In tkinter:

 Use tk.Checkbutton.

 Each checkbox has its own variable (often tk.IntVar() or tk.BooleanVar()).

Example: Check Buttons

import tkinter as tk

root = tk.Tk()

root.title("Check Button Example")

# Variables to track checkbox states

var1 = tk.IntVar()

var2 = tk.IntVar()

var3 = tk.IntVar()

# Create check buttons

tk.Checkbutton(root, text="Check 1", variable=var1).pack()

tk.Checkbutton(root, text="Check 2", variable=var2).pack()

tk.Checkbutton(root, text="Check 3", variable=var3).pack()

root.mainloop()

Main differences:
Feature Radio Button Check Button

Multiple options at the same


Selection Only one option at a time.
time.

Linked variable Shared (same variable for all buttons). Each has its own variable.

Choose one from a group (e.g.,


Common use case Select many (e.g., hobbies).
gender).

Canvas in Python GUI

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 = tk.Canvas(root, width=300, height=200, bg="white")

canvas.pack()

# Draw shapes

canvas.create_line(10, 10, 200, 10, fill="blue", width=3)

canvas.create_rectangle(50, 50, 150, 100, fill="red")

canvas.create_oval(50, 120, 150, 180, fill="green")

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").

tk.Tk() sets up the window.

root.title("Canvas Example") sets the title bar text.

# Create a canvas

canvas = tk.Canvas(root, width=300, height=200, bg="white")

canvas.pack()

➡️This creates the Canvas widget:

tk.Canvas(root, ...) creates a drawing area inside the main window.

width=300, height=200 sets its size (300 pixels wide, 200 pixels tall).

bg="white" sets the background color to white.

.pack() adds it to the window so it appears on the screen.

# Draw shapes

canvas.create_line(10, 10, 200, 10, fill="blue", width=3)

➡️This draws a line:

Starts at (10, 10) and ends at (200, 10).

fill="blue" makes the line blue.

width=3 sets the line thickness.

canvas.create_rectangle(50, 50, 150, 100, fill="red")

➡️This draws a rectangle:

The rectangle’s top-left corner is at (50, 50).

The bottom-right corner is at (150, 100).

fill="red" fills the rectangle with red color.

canvas.create_oval(50, 120, 150, 180, fill="green")


➡️This draws an oval:

The oval fits inside the rectangle from (50, 120) to (150, 180).

fill="green" fills it with green color.

root.mainloop()

➡️This starts the GUI event loop:

Keeps the window open, waiting for any user action (like closing it).

Without this, the window would flash and close immediately.

Menus in Python GUI

What are Menus?

 A menu is a list of options or commands at the top of the window (like File, Edit,
etc.).

 Menus help you organize commands in a clean way.

import tkinter as tk

def new_file():

print("New File Created!")

def open_file():

print("File Opened!")

def exit_app():

root.destroy()

root = tk.Tk()

root.title("Menu Example")

# Create a menu bar

menu_bar = tk.Menu(root)

# Create a "File" menu

file_menu = tk.Menu(menu_bar, tearoff=0)

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)

# Add the "File" menu to the menu bar

menu_bar.add_cascade(label="File", menu=file_menu)

# Attach the menu bar to the root window

root.config(menu=menu_bar)

root.mainloop()

EXPLANATION

import tkinter as tk

➡️This imports the tkinter library, which you use to build the GUI.

Define the functions:

def new_file():

print("New File Created!")

def open_file():

print("File Opened!")

def exit_app():

root.destroy()

These are functions that run when a menu item is clicked:

new_file(): Prints a message saying a new file is created.

open_file(): Prints a message saying a file is opened.

exit_app(): Closes the window using root.destroy().

Create the main window:

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:

# Create a menu bar

menu_bar = tk.Menu(root)

➡️You create a menu bar object that will hold all your menus (like "File", "Edit", etc.).

Create the "File" menu:

file_menu = tk.Menu(menu_bar, tearoff=0)

➡️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).

Add items to the File menu:

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)

add_command: Adds a menu item with a label and links it to a function.

"New" runs new_file().

"Open" runs open_file().

"Exit" runs exit_app().

add_separator(): Adds a horizontal line to visually separate menu items.

🔗 Add File menu to the menu bar:

menu_bar.add_cascade(label="File", menu=file_menu)

➡️This adds the File menu (the dropdown) to the menu bar, with the label "File."

Attach the menu bar to the window:

root.config(menu=menu_bar)

➡️This tells the window to display the menu bar you just created.

▶️Run the main loop:

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:

 NumPy: For numerical computing and handling arrays.

 pandas: For data manipulation and analysis (works well with tables/dataframes).

 matplotlib: For plotting and data visualization.

 SciPy: For scientific computing (builds on NumPy with advanced math, stats,
optimization, etc.).

1️.NumPy

What it is:

 Stands for Numerical Python.

 Used for fast mathematical operations on large arrays and matrices.

✅ Key feature:

 Efficient handling of multi-dimensional arrays.

🔧 Example: NumPy Array

import numpy as np

# Create a NumPy array

arr = np.array([1, 2, 3, 4, 5])

print(arr * 2) # Multiply each element by 2

Output:

[ 2 4 6 8 10]

2️.pandas

What it is:

 Great for data manipulation and analysis.

 Especially good for working with tabular data (like Excel sheets).
✅ Key feature:

 Uses DataFrames (tables with rows and columns).

🔧 Example: pandas DataFrame

import pandas as pd

# Create a DataFrame

data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}

df = pd.DataFrame(data)

print(df)

Output:

markdown

Name Age

0 Alice 25

1 Bob 30

3️.matplotlib

What it is:

 Python’s most popular library for plotting.

 Great for making charts and graphs.

✅ Key feature:

 Can create line charts, bar graphs, pie charts, etc.

🔧 Example: Simple Plot

import matplotlib.pyplot as plt

# Data

x = [1, 2, 3, 4]
y = [2, 4, 6, 8]

# Plot

plt.plot(x, y)

plt.title("Simple Line Plot")

plt.show()

4️.SciPy

What it is:

 Stands for Scientific Python.

 Adds advanced math functions on top of NumPy (like integration, optimization,


signal processing).

✅ Key feature:

 Used for scientific and engineering calculations.

🔧 Example: SciPy Integration

from scipy import integrate

# Define a simple function

def f(x):

return x ** 2

# Integrate from 0 to 1

result, error = integrate.quad(f, 0, 1)

print(result)

Output:

0.33333333333333337

In summary:
Library Main Use Key Object / Feature

NumPy Fast array operations ndarray (arrays)

pandas Handling structured (tabular) data DataFrame

matplotlib Plotting and visualization Charts and plots

SciPy Advanced scientific computing (math, stats, etc.) Integrate, optimize, etc.

import matplotlib.pyplot as plt # Data x = [1, 2, 3, 4] y = [2, 4, 6, 8] # Plot plt.plot(x, y)


plt.title("Simple Line Plot") plt.show() show output

What the plot looks like:

 A 2D line chart with:

o x-axis labeled with points: 1, 2, 3, 4.

o y-axis labeled with points: 2, 4, 6, 8.

 A straight diagonal line passing through points:

o (1, 2)

o (2, 4)

o (3, 6)

o (4, 8)

 The chart title is:

o "Simple Line Plot"

The result is a simple line plot showing a straight, upward-sloping line, because y increases
in direct proportion to x (y = 2x).

numpy intsallation process with explanation

Great question! Let’s go through the NumPy installation process step by step, along with a
simple explanation.

1️.nstall using pip (the easiest way)


If you already have Python and pip installed, you can install NumPy by running this
command in your terminal or command prompt:

pip install numpy

What happens:

 pip downloads NumPy from the Python Package Index (PyPI).

 It installs NumPy and all its required files so you can import and use it in your Python
programs.

2️.Check if it’s installed

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).

3️.If you are using Anaconda (conda environment)

If you’re using Anaconda, you can install NumPy using:

conda install numpy

This is especially useful because Anaconda handles all dependencies and is often better for
scientific computing.

Common installation issues:

 pip not recognized?

o Make sure Python and pip are added to your system’s PATH.

 Older Python version?

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:

 Handle arrays/matrices efficiently,

 Do mathematical and statistical operations,

 Enable fast computation (much faster than regular Python lists).

Creating NumPy ndarray (n-dimensional array)

What is ndarray?

 In NumPy, an ndarray (n-dimensional array) is a powerful data structure that can


hold items of the same data type.

 It allows for fast, efficient mathematical and logical operations on large datasets.

How to create an ndarray

You first need to import NumPy:

import numpy as np

1️.Creating from a Python list

You can convert a regular Python list (or a list of lists) into an ndarray:

arr1 = np.array([1, 2, 3, 4])

print(arr1)

Output:

[1 2 3 4]

This is a 1D array.

2️.Creating a 2D array

arr2 = np.array([[1, 2, 3], [4, 5, 6]])

print(arr2)
Output:

[[1 2 3]

[4 5 6]]

This is a 2D array (matrix).

3️.Creating a 3D array

arr3 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

print(arr3)

This is a 3D array (tensor-like structure).

Special arrays using NumPy functions

a) Zeros array

Creates an array full of zeros:

zeros_arr = np.zeros((2, 3))

print(zeros_arr)

b) Ones array

Creates an array full of ones:

ones_arr = np.ones((3, 3))

print(ones_arr)

c) Array with a range

range_arr = np.arange(1, 10, 2)

print(range_arr)

Output: [1 3 5 7 9]

d) Identity matrix

identity_arr = np.eye(3)
print(identity_arr)

Creates a 3×3 identity matrix.

Checking the shape and dimension

print(arr2.shape) # (2, 3)

print(arr2.ndim) # 2

 .shape tells you the array’s size (rows, columns).

 .ndim tells you the number of dimensions.

In summary:

Method Example Code Description

From list np.array([1,2,3]) Creates ndarray from list

Zeros array np.zeros((2,3)) 2x3 array of zeros

Ones array np.ones((3,3)) 3x3 array of ones

Range array np.arange(1,10,2) Numbers from 1 to 9 with step 2

Identity matrix np.eye(3) 3x3 identity matrix

✅ 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

arr3 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

print(arr3)

The output will be:

[[[1 2]
[3 4]]

[[5 6]

[7 8]]]

Explanation:

 This is a 3D array:

o The first block: [[1, 2], [3, 4]]

o The second block: [[5, 6], [7, 8]]

 You can think of it as 2 "layers," each containing a 2×2 matrix.

import numpy as np

zeros_arr = np.zeros((2, 3))

print(zeros_arr)

The output will be:

[[0. 0. 0.]

[0. 0. 0.]]

Explanation:

 This creates a 2×3 array (2 rows, 3 columns) filled with zeros.

 The numbers are shown as 0. (with a decimal point) because NumPy defaults to float
type unless specified otherwise.

import numpy as np

ones_arr = np.ones((3, 3))


print(ones_arr)

The output will be:

[[1. 1. 1.]

[1. 1. 1.]

[1. 1. 1.]]

Explanation:

 This creates a 3×3 array (like a square matrix) filled with 1.0.

 The values are shown as floating point numbers (1.) by default.

Arithmetic with NumPy Arrays

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.

Basic Arithmetic Operations

Let’s assume we have two arrays:

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:

[0.25 0.4 0.5 ]

Operations with Scalars

Example:

result = a * 10

print(result)

Output:

[10 20 30]

This multiplies each element by 10.


Other Mathematical Functions

 Square root:

print(np.sqrt(a))

 Exponentiation:

print(a ** 2)

 Sine:

print(np.sin(a))

Broadcasting

NumPy allows operations between arrays of different shapes using broadcasting.

Example:

matrix = np.array([[1, 2, 3], [4, 5, 6]])

vector = np.array([1, 0, 1])

result = matrix + vector

print(result)

Output:

[[2 2 4]

[5 5 7]]

NumPy automatically "stretches" the smaller array to match the shape.

In Summary:

 NumPy allows fast, element-wise arithmetic.

 Supports both array-to-array and array-to-scalar operations.

 Functions like np.sqrt(), np.sin(), etc., can be applied directly to arrays.

 Broadcasting makes operations between different-shaped arrays possible.

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).

🔹 Example with a string:

text = "Hello"

print(text[0]) # Output: 'H'

print(text[-1]) # Output: 'o'

🔹 Example with a list:

fruits = ["apple", "banana", "cherry"]

print(fruits[1]) # Output: 'banana'

print(fruits[-2]) # Output: 'banana'

Slicing

Slicing means extracting a portion of a sequence using the syntax:

sequence[start:stop:step]

 start: index where the slice starts (inclusive)

 stop: index where the slice ends (exclusive)

 step: how many items to move forward (default is 1)

🔹 Example with a string:

text = "Hello World"

print(text[0:5]) # Output: 'Hello'

print(text[6:]) # Output: 'World'

print(text[:5]) # Output: 'Hello'

print(text[::2]) # Output: 'HloWrd'

🔹 Example with a list:

numbers = [10, 20, 30, 40, 50, 60]


print(numbers[1:4]) # Output: [20, 30, 40]

print(numbers[:3]) # Output: [10, 20, 30]

print(numbers[::2]) # Output: [10, 30, 50]

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.

🔹 Example with a List:

data = [10, 20, 30, 40, 50]

condition = [True, False, True, False, True]

# Apply boolean indexing

result = [d for d, c in zip(data, condition) if c]

print(result) # Output: [10, 30, 50]

⚠️Plain Python lists don't support direct boolean indexing like NumPy arrays do, so you
need a loop or list comprehension as above.

🔹 Example with NumPy (More Common):

import numpy as np

data = np.array([10, 20, 30, 40, 50])

# Create a boolean mask: select elements > 25


mask = data > 25

print(mask) # Output: [False False True True True]

# Apply boolean indexing

print(data[mask]) # Output: [30 40 50]

You can even do it all in one line:

print(data[data > 25]) # Output: [30 40 50]

🔹 Example with Pandas (DataFrames):

import pandas as pd

df = pd.DataFrame({

'name': ['Alice', 'Bob', 'Charlie'],

'age': [25, 17, 30]

})

# Boolean indexing: select rows where age > 18

adults = df[df['age'] > 18]

print(adults)

Output:

name age

0 Alice 25

2 Charlie 30

Summary:

 Boolean indexing = filter data using conditions.

 Widely used in data analysis, filtering arrays, and conditional selection.

 Most powerful when used with NumPy or Pandas.


Transposing Arrays

Transposing means flipping an array over its diagonal:

 Rows become columns

 Columns become rows

It’s most commonly used with 2D arrays, like matrices.

🔹 Example using NumPy:

import numpy as np

arr = np.array([[1, 2, 3],

[4, 5, 6]])

# Transpose the array

transposed = arr.T

print(transposed)

Output:

[[1 4]

[2 5]

[3 6]]

You can also use:

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]]

])

This is a 3D array of shape (2, 2, 2):

 2 blocks (axis 0)

 Each block has 2 rows (axis 1)

 Each row has 2 columns (axis 2)

Think of it like:

arr[0] = [[1, 2],

[3, 4]]

arr[1] = [[5, 6],

[7, 8]]

🔸 Swap axis 0 and 2:

swapped = np.swapaxes(arr, 0, 2)

This swaps:

 Axis 0 (the outermost layer — the two blocks)

 Axis 2 (the innermost layer — individual numbers in each row)

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:

Original [i, j, k] Value New [k, j, i]

[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]

Pseudorandom Number Generation (PRNG) — Explained Simply

Pseudorandom number generation is the process of producing numbers that appear


random but are generated using a deterministic algorithm (i.e., they are not truly random
but follow a repeatable pattern).

🔸 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:

1. Start with a seed value (could be time-based or user-defined).

2. Apply a mathematical formula to produce a number.

3. That number becomes input for the next number.

4. Repeat.

🔸 In Python — Using the random module:

import random

# Set a seed for reproducibility

random.seed(42)

# Generate pseudorandom numbers

print(random.randint(1, 100)) # Same output every time with same seed

print(random.random()) # Random float between 0 and 1

Output (will always be the same if seed is the same):

82

0.6394267984578837

🔸 In NumPy — Better for Arrays:

import numpy as np

np.random.seed(0)
# Generate random integers

print(np.random.randint(1, 10, size=5)) # [6 1 4 4 8]

🔹 Real vs Pseudorandom

Feature Pseudorandom Truly Random

Deterministic Yes No

Repeatable Yes (with seed) No

Speed Fast Often slower

Use cases Games, simulations Cryptography (needs true randomness)

🔸 Summary:

 Pseudorandom ≠ truly random

 Fast and good enough for most tasks (e.g., games, simulations)

 Use random.seed() or np.random.seed() for reproducible results

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).

What Are Universal Functions (ufuncs)?

 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.

🔸 Examples of Universal Functions (ufuncs):

1. Arithmetic Functions:
These functions perform element-wise arithmetic operations like addition,
subtraction, etc.

2. import numpy as np
3.

4. # Example array

5. arr = np.array([1, 2, 3, 4, 5])

6.

7. # Adding 10 to each element of the array

8. result = np.add(arr, 10) # Element-wise addition

9. print(result) # Output: [11 12 13 14 15]

10. Trigonometric Functions:

11. arr = np.array([0, np.pi / 2, np.pi])

12.

13. # Taking the sine of each element

14. result = np.sin(arr)

15. print(result) # Output: [ 0. 1. 0.]

16. Exponential and Logarithmic Functions:

17. arr = np.array([1, 2, 3])

18.

19. # Calculate the exponential of each element

20. result = np.exp(arr)

21. print(result) # Output: [ 2.71828183 7.3890561 20.08553692]

22.

23. # Calculate the natural logarithm of each element

24. result = np.log(arr)

25. print(result) # Output: [0. 0.69314718 1.09861229]

🔸 Broadcasting and Scalar Operations:

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.

arr = np.array([1, 2, 3, 4])


# Scalar multiplication

result = arr * 2 # Multiply each element by 2

print(result) # Output: [2 4 6 8]

🔸 Custom Universal Functions (ufuncs):

You can also define your own ufuncs in NumPy using np.frompyfunc() or by creating an
operation with vectorize.

Example of a Custom ufunc:

# Define a simple custom function

def custom_function(x):

return x**2 + 2*x + 1

# Make it a universal function

ufunc = np.frompyfunc(custom_function, 1, 1)

arr = np.array([1, 2, 3, 4])

result = ufunc(arr)

print(result) # Output: [ 4 9 16 25]

📌 Summary of Universal Functions (ufuncs):

 ufuncs allow fast, element-wise operations on NumPy arrays.

 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.

You might also like