Tiny Book On Python by ChatGPT Edited by MRS
Tiny Book On Python by ChatGPT Edited by MRS
Python Programming
This is a tiny book on “Python Programming” — suitable for university level 1st or 2nd
year students (especially non-Computer Science background). It’s written in a teaching
style, with explanations, examples, and short exercises.
Written By
ChatGPT 5.0
Editor
October 2025
i
Table of contents
2.5 Strings 6
2.9 Constants 7
2.11 Exercises 8
2.12 Summary 9
🕐 Lecture Outline 10
ii
🔹 6. Bitwise Operators (30 minutes) 13
Exercises 16
Review Questions 17
🏁 Summary 17
1. Introduction 18
2. Input in Python 18
3. Output in Python 20
7. Summary 22
8. Exercises 22
2. What is a Condition? 24
3. Comparison Operators 24
4. Logical Operators 24
5. The if Statement 25
iii
6. The if-else Statement 25
8. Nested if Statements 26
15. Summary 29
16. Exercises 29
8. Infinite Loops 36
iv
12. Exercises (Gradually Increasing Difficulty) 37
14. Summary 39
2. Types of Functions 40
3. Defining a Function 40
5. Return Statement 41
6. Types of Arguments 41
10. Recursion 43
13. Exercises 45
14. Summary 46
Chapter 8: Strings 47
🎯 Learning Objectives 47
🕐 Lecture Outline 47
v
🔹 4. String Methods (30 minutes) 50
Exercises 54
Review Questions 54
🏁 Summary 54
1. What is a Set? 68
🔧 4. Modifying Sets 69
🔍 6. Set Membership 70
vi
🔗 7. Frozen Set (Immutable Set) 70
📘 8. Example Program 70
💡 9. Key Properties 71
Exercise 1 71
Exercise 2 72
Exercise 3 72
Exercise 4 73
💡 Bonus Challenge 73
2. Creating Tuples 74
🔄 4. Tuple Operations 75
⚙ 7. Immutability of Tuples 76
8. Tuples vs Lists 77
13. Exercises 78
14. Summary 78
vii
Chapter 12: Dictionaries in Python 80
🎯 Learning Objectives 80
Chapter Outline 80
Exercises 85
Review Questions 86
🏁 Summary 86
⚙ 2. Similarities 87
🔍 3. Key Differences 87
5. Example Comparison 89
6. Summary Table 89
viii
Chapter 1: Introduction to Python
1.1 What is Python?
Python emphasizes readability, simplicity, and flexibility, which makes it ideal for
beginners as well as professionals.
1
1.5 Writing and Running Python Programs
Indentation:
Python uses indentation instead of braces {} to define blocks.
if 5 > 2:
print("Five is greater than two!") # Correct
Comments:
"""
This is a
multi-line comment
"""
x = 10 # int
name = "Alice" # str
pi = 3.1416 # float
2
1.9 Example Program
# Program to calculate area of a circle
Output:
Enter radius: 5
Area = 78.54
Advantages:
Limitations:
1.11 Exercise
1.12 Summary
3
Chapter 2: Variables and Data Types in Python
2.1 Introduction
In any programming language, variables and data types form the foundation.
They are how we store, organize, and work with data in a program.
Python is special because it is dynamically typed – meaning you don’t need to declare
the type of a variable before using it.
The interpreter automatically determines the type from the value you assign.
It acts as a container to hold data that can be used and modified later.
Example:
x = 10
y = 3.5
name = "Alice"
Here:
✅Valid:
name, _value, age2, student_name
❌Invalid:
2name, student name, class
4
2.2.2 Multiple Assignments
a, b, c = 10, 20, 30
print(a, b, c)
x = y = z = 5
print(x, y, z)
A data type defines the kind of value a variable holds and what operations can be
performed on it.
You can check the data type using the type() function.
x = 10
y = 3.14
z = "Python"
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'int'>
<class 'float'>
<class 'str'>
5
3. complex — numbers with real and imaginary parts
Example:
a = 5
b = 3.2
c = 2 + 4j
print(a + b)
print([Link], [Link])
2.5 Strings
A string is a sequence of characters enclosed in single (' '), double (" "), or triple
quotes (''' ''' / """ """).
Examples:
name = "Alice"
message = 'Hello World'
paragraph = """This is
a multiline
string."""
String operations:
name = "Python"
print(name[0]) # P
print(name[-1]) # n
print(name[1:4]) # yth
print(len(name)) # 6
x = True
y = False
print(x and y) # False
print(x or y) # True
6
# int to float
a = 5
b = float(a)
print(b) # 5.0
# float to int
x = 3.7
y = int(x)
print(y) # 3
# int to str
n = 25
s = str(n)
print("Value is " + s)
2.9 Constants
Python does not have built-in constant types, but by convention, constants are written in
uppercase.
PI = 3.1416
GRAVITY = 9.8
(Python doesn’t stop you from changing them, but you shouldn’t!)
7
average = (a + b + c) / 3
print("Average =", average)
si = (p * r * t) / 100
print("Simple Interest =", si)
print("Years:", years)
print("Weeks:", weeks)
print("Days:", remaining_days)
2.11 Exercises
Part A: Conceptual
1. What is a variable?
2. Why is Python called dynamically typed?
3. What is the difference between int and float?
4. Give examples of valid and invalid variable names.
5. What is the purpose of type casting?
8
2.12 Summary
9
Chapter 3: Operators and Expressions
🎯 Learning Objectives
🕐 Lecture Outline
Time Topic
10
🔹 1. Introduction to Operators and Expressions (20 minutes)
What is an Operator?
Example:
a = 10
b = 3
result = a + b # '+' is an operator, a and b are operands
What is an Expression?
Examples:
3 + 5 * 2
(a + b) / 2
x > 5 and y < 10
Example Program 1
a = 12
b = 5
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Power:", a ** b)
11
Real-Life Example
# Calculate area and perimeter of a rectangle
length = 5
width = 3
area = length * width
perimeter = 2 * (length + width)
print("Area:", area)
print("Perimeter:", perimeter)
Example Program 2
a = 10
b = 20
print(a == b)
print(a != b)
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)
12
Example Program 3
x = 10
x += 5
print("After += :", x)
x *= 2
print("After *= :", x)
x -= 4
print("After -= :", x)
Example Program 4
age = 20
country = "Bangladesh"
Note:
5 → binary 0101
3 → binary 0011
13
Example Program 5
a = 5
b = 3
print("a & b =", a & b)
print("a | b =", a | b)
print("a ^ b =", a ^ b)
print("~a =", ~a)
print("a << 1 =", a << 1)
print("a >> 1 =", a >> 1)
Example
x = [1, 2, 3]
y = [1, 2, 3]
z = x
Used to test whether a value exists in a sequence (string, list, tuple, etc.).
Example
fruits = ["apple", "banana", "mango"]
print("banana" in fruits)
print("orange" not in fruits)
14
🔹 9. Operator Precedence and Associativity (30 minutes)
Example Program 6
result = 10 + 3 * 2
print(result) # 16 (3*2=6, then 10+6)
To override precedence:
result = (10 + 3) * 2
print(result) # 26
Simple Expression
x = 5
y = 3
z = x**2 + y*3 - 4
print(z)
Compound Expression
a = 10
b = 5
c = 2
result = (a + b) * c / (a - b)
print(result)
Boolean Expression
x = 4
print((x > 2) and (x < 6)) # True
15
🔹 11. Practical Examples (30 minutes)
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Remainder:", a % b)
Exercises
Part A – Basic
Part B – Intermediate
Part C – Advanced
7. Build a program that takes marks and assigns grade (A/B/C/F) using relational
operators.
8. Use membership and identity operators to differentiate two lists with same
contents.
9. Write a program that calculates the binary AND, OR, and XOR of two numbers.
16
Review Questions
🏁 Summary
17
Chapter 4: Input and Output in Python
⏱Duration:
1. Introduction
Every program needs a way to interact with the user or the outside world.
In Python:
2. Input in Python
Syntax:
Output:
18
2.2 Type Conversion (Casting)
Conversion Function
Integer int()
Float float()
String str()
Example 3:
Output:
Example 4:
Output:
19
3. Output in Python
Syntax:
Parameters:
Example 5:
Output:
Python is fun
Python-is-fun!
Example 6:
name = "Selim"
age = 25
print("Name:", name, ", Age:", age)
20
(d) Using f-Strings (Python 3.6+)
name = "Reza"
marks = 85
print(f"{name} scored {marks} marks.")
Output:
21
5. Output Formatting for Tables
Example 11:
print(f"{'Name':<10}{'Marks':>5}")
print(f"{'Alice':<10}{95:>5}")
print(f"{'Bob':<10}{88:>5}")
Output:
Name Marks
Alice 95
Bob 88
Although we’ll discuss File I/O in detail later, here’s a short preview.
Writing to a File
f = open("[Link]", "w")
[Link]("Hello, Python!\n")
[Link]("This is file writing example.")
[Link]()
7. Summary
Topic Function / Concept Example
Input from user input() x = input()
Convert to int int() n = int(input())
Print output print() print("Hello")
Separator sep print("A", "B", sep='-')
End parameter end print("Hi", end='!')
Format string f"..." f"{x:.2f}"
8. Exercises
Exercise 1:
Write a program that asks your name and prints a greeting message.
22
Exercise 2:
Take two numbers from the user and print their sum, difference, product, and quotient.
Exercise 3:
Exercise 4:
Take three subject marks and print the average and grade.
Exercise 5:
Ask the user to enter 5 numbers and print them in reverse order.
Exercise 6 (Advanced):
23
Chapter 5: Conditional Statements in Python
1. Introduction
2. What is a Condition?
Examples:
5 > 3 # True
10 < 7 # False
x == 10 # True if x equals 10
Conditions are built using comparison operators and sometimes logical operators.
3. Comparison Operators
Operator Meaning Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 5 > 3 True
< Less than 5 < 3 False
>= Greater than or equal to 5 >= 5 True
<= Less than or equal to 3 <= 5 True
4. Logical Operators
Operator Meaning Example Result
and True if both conditions are true (x > 0 and y > 0) True if both
are positive
24
or True if any one condition is true (x > 0 or y > 0) True if either
is positive
not Reverses the condition not(x > 0) True if x ≤ 0
5. The if Statement
Syntax:
if condition:
statement(s)
If the condition is True, the indented block runs; otherwise, it’s skipped.
Example 1:
x = 10
if x > 0:
print("Positive number")
Output:
Positive number
If x = -3, no output.
Syntax:
if condition:
statements_if_true
else:
statements_if_false
Example 2:
x = int(input("Enter a number: "))
if x % 2 == 0:
print("Even number")
else:
print("Odd number")
Syntax:
if condition1:
25
statements1
elif condition2:
statements2
elif condition3:
statements3
else:
statements_else
Example 3:
marks = int(input("Enter marks: "))
print("Grade:", grade)
8. Nested if Statements
Example 4:
num = int(input("Enter a number: "))
if num > 0:
if num % 2 == 0:
print("Positive even number")
else:
print("Positive odd number")
else:
print("Not a positive number")
When you need a block but don’t want to write code yet, use pass.
Example 5:
x = 10
if x > 0:
pass # future code will go here
else:
print("Negative number")
26
10. Conditional Expressions (Ternary Operator)
Syntax:
value_if_true if condition else value_if_false
Example 6:
a = 5
b = 10
max_value = a if a > b else b
print("Maximum:", max_value)
Output:
Maximum: 10
Example 7:
age = int(input("Enter age: "))
Example 8:
password = input("Enter password: ")
if password == "python123":
print("Access granted")
else:
print("Access denied")
27
if a >= b and a >= c:
largest = a
elif b >= a and b >= c:
largest = b
else:
largest = c
if op == '+':
print("Result:", a + b)
elif op == '-':
print("Result:", a - b)
elif op == '*':
print("Result:", a * b)
elif op == '/':
if b != 0:
print("Result:", a / b)
else:
print("Division by zero not allowed")
else:
print("Invalid operator")
28
14. Common Mistakes
Mistake Problem Correction
Using = instead of == if x = 10: ❌ if x == 10: ✅
Forgetting indentation if x > 0: print("Positive") Use indentation (4 spaces
(same line) or Tab)
Not converting input if input() > 10: ❌ (string if int(input()) > 10:
comparison) ✅
15. Summary
Concept Keyword Example
Simple condition if if x > 0:
Two-way choice if-else if x%2==0: else:
Multiple conditions elif if-elif-else
Nested decisions if inside if see example
Do nothing yet pass if x>0: pass
Short condition ternary operator a if cond else b
16. Exercises
Exercise 1:
Exercise 2:
“Child” if under 12
“Teenager” if 13–19
“Adult” if 20–59
“Senior” if 60 or above
Exercise 3:
Exercise 4:
Exercise 5:
Ask a user for their username and password, and grant access only if both are correct.
29
Exercise 6:
Exercise 7:
< 0 → “Freezing”
0–20 → “Cold”
21–35 → “Warm”
35 → “Hot”
Exercise 8 (Challenge):
30
Chapter 6: Loops in Python
In programming, when you need to repeat a block of code multiple times, you use
loops.
Without loops, we’d have to repeat code manually — inefficient and error-prone.
1. for loop — used when you know how many times to repeat.
2. while loop — used when you want to repeat until a condition becomes false.
There is also:
31
3.2. Example 1: Print numbers 1 to 5
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Output:
2
4
6
8
10
Output:
Sum = 55
32
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Output:
33
4.3. Example 2: Sum of first 10 numbers
i = 1
sum = 0
while i <= 10:
sum += i
i += 1
print("Sum:", sum)
Output: 1 2 3 4
Output: 1 2 3 4 6 7 8 9
34
pass # To be implemented later
Syntax:
for/while ...:
# loop body
else:
# executes when loop finishes normally (no break)
Example:
for i in range(5):
print(i)
else:
print("Loop completed successfully!")
Output:
*
**
***
****
*****
result = [[0,0,0],
[0,0,0]]
for i in range(2):
for j in range(3):
result[i][j] = A[i][j] + B[i][j]
35
print("Resultant Matrix:")
for r in result:
print(r)
8. Infinite Loops
Example:
while True:
print("This will never end!")
36
while count < n:
print(a)
a, b = b, a + b
count += 1
if flag == 0:
print("Prime number")
else:
print("Not a prime number")
Beginner
37
5. Display a multiplication table for any number.
Intermediate
Advanced
*****
****
***
**
*
38
14. Summary
Shorter
Easier to modify
Efficient
Knowing when to use for or while, and controlling flow using break, continue, and
else are essential for structured programming.
39
Chapter 7: Functions in Python
1. Introduction
2. Types of Functions
3. Defining a Function
Syntax:
def function_name(parameters):
"""docstring (optional): describes what the function does"""
statement(s)
return value
Example 1:
def greet():
print("Hello, welcome to Python!")
Output:
40
4. Function Parameters and Arguments
Parameters are variables that receive values when the function is called.
Example 2:
def greet(name):
print("Hello", name, "!")
Output:
Hello Alice !
Hello Rahim !
5. Return Statement
Example 3:
def add(a, b):
sum = a + b
return sum
Output:
Sum = 15
6. Types of Arguments
Type Description Example
Positional arguments Values passed in order add(3,4)
Keyword arguments Values passed by name add(b=4, a=3)
Default arguments Values assigned automatically if not def add(a, b=10):
passed return a+b
Variable-length Used when number of arguments is *args or **kwargs
arguments unknown
41
Output:
Hello Guest
total(2, 3, 5)
total(1, 2, 3, 4, 5)
Output:
Sum = 10
Sum = 15
Example 6:
x = 10 # global variable
def show():
x = 5 # local variable
print("Inside function:", x)
show()
print("Outside function:", x)
Output:
Inside function: 5
Outside function: 10
def modify():
global x
x = x + 5
modify()
print("After modify:", x)
Output:
42
After modify: 15
Example 7:
def calc(a, b):
return a+b, a-b, a*b, a/b
Output:
Sum: 15
Difference: 5
Product: 50
Quotient: 2.0
Syntax:
lambda arguments: expression
Example 8:
square = lambda x: x*x
print(square(5))
Output:
25
Example 9:
add = lambda a, b: a + b
print(add(3, 4))
Output:
10. Recursion
43
Example 10: Factorial using recursion
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
Output:
Factorial of 5: 120
Example:
File: math_utils.py
Main program:
import math_utils
print(math_utils.add(4, 5))
44
Example 3: Prime check
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
13. Exercises
Part A: Basic
Part B: Intermediate
Part C: Advanced
9. Write a function that accepts a list of marks and returns grade ( A, B, C, F) based on
average.
10. Create a function fibonacci(n) that prints the Fibonacci series up to n.
11. Write a lambda function that returns the cube of a number.
12. Write a recursive function to compute the greatest common divisor (GCD).
45
14. Summary
Concept Description
Function Block of code that performs a specific task
Parameters Values received by a function
Return Sends result back to caller
Local/Global Variables Scope of variable visibility
Lambda Anonymous, short functions
Recursion Function calling itself
✅Learning Outcome:
By the end of this lecture, students should be able to:
46
Chapter 8: Strings
Duration: 2–3 Hours
Prerequisite: Basic understanding of Python variables and data types
🎯 Learning Objectives
1. Understand what strings are and how they are stored in Python.
2. Create, access, and manipulate strings.
3. Use string operators and built-in methods.
4. Format strings effectively.
5. Work with escape characters and multiline strings.
6. Solve small programming problems using strings.
🕐 Lecture Outline
Time Topic
47
Time Topic
What is a String?
Example:
name = "Alice"
message = 'Hello, world!'
info = """This is a multiline string."""
String Examples
city = "Dhaka" print(type(city)) # <class 'str'> print(len(city)) # 5
Creating Strings
s1 = 'Hello'
s2 = "World"
s3 = """This is a multiline string."""
word = "Python"
48
print(word[0]) # P
print(word[3]) # h
print(word[-1]) # n print(word[-2]) # o
Slicing Strings
print(text[::2]) # 'Bnlah'
Example Program 1
country = "Bangladesh"
print("First 3 letters:", country[:3])
print("Last 4 letters:", country[-4:])
print("Middle part:", country[3:7])
String Concatenation
a = "Hello"
b = "World"
print(a + " " + b) # Hello World
String Repetition
print("Hi! " * 3) # Hi! Hi! Hi!
Membership Operators
sentence = "Python is fun" print("Python" in sentence) # True
print("Java" not in sentence) # True
49
Example Program 2: Combine Names
first = input("Enter first name: ") last = input("Enter last name: ")
print("Full Name:", first + " " + last)
50
Output:
ALICE
Example Program 5
product = "Laptop"
price = 85000.5
print(f"The price of {product} is {price:.2f} Taka.")
Output:
51
🔹 6. Escape Sequences & Multiline Strings (25 minutes)
Escape Sequences
\n Newline "Hello\nWorld"
\t Tab "Name\tAge"
\\ Backslash "C:\\Users"
Example:
print("Name\tDept\nRahim\tCSE\nKarim\tEEE")
Output:
Name Dept
Rahim CSE
Karim EEE
Multiline Strings
text = """This is a string that spans multiple lines."""
print(text)
52
print("Not a palindrome")
53
Exercises
Part A – Basic
1. Create a string variable and print its first, last, and middle characters.
2. Take user input and print it in uppercase, lowercase, and title case.
3. Find how many times “a” appears in the word “banana”.
Part B – Intermediate
4. Write a program that reverses a string entered by the user.
5. Ask for a sentence and count how many words it contains.
6. Replace all spaces in a sentence with underscores _.
Part C – Advanced
7. Write a program that checks if a string starts and ends with the same character.
8. Build a small program that asks for a password and checks whether it:
Has at least 8 characters
Contains both uppercase and lowercase letters
Contains at least one digit
Review Questions
1. What is meant by “strings are immutable”?
2. What is the difference between indexing and slicing?
3. How do split() and join() work together?
4. What is the output of "abc" * 3?
5. How can you safely insert variables into a string?
🏁 Summary
A string is a sequence of characters enclosed in quotes.
Strings are immutable, meaning you can’t change characters directly.
You can access, slice, concatenate, and format strings easily.
Python provides many methods to manipulate and analyze strings.
Strings are one of the most used data types in all programming tasks.
54
Chapter 9: Python Lists
🎯 Learning Objectives
🔹 1. What is a List?
# Example
my_list = [10, "Hello", 3.14, True]
🔹 2. Creating Lists
# Empty list
a = []
# With elements
b = [1, 2, 3, 4]
# Nested list
d = [[1, 2], [3, 4]]
🔹 3. Accessing Elements
55
Python uses zero-based indexing.
print(numbers[0]) # 10
print(numbers[-1]) # 50 (last element)
🔹 4. List Slicing
🔹 5. Modifying Lists
numbers[2] = 99
[Link](60)
[Link](1, 15)
[Link](99)
del numbers[0]
56
🔹 7. Iterating Through Lists
fruits = ["apple", "banana", "cherry"]
for f in fruits:
print(f)
Using enumerate():
for i, f in enumerate(fruits):
print(i, f)
🔹 8. List Comprehension
🔹 9. Copying Lists
a = [1, 2, 3]
b = a # both point to same list
b[0] = 99
print(a) # [99, 2, 3]
# Correct way
c = [Link]()
c[0] = 10
print(a) # [99, 2, 3]
print(c) # [10, 2, 3]
57
🔹 11. Nested Lists (Matrix)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][2]) # 6
Exercise
1. Create a list of integers and print the sum of all even numbers.
2. Reverse a list without using the reverse() function.
3. Write a list comprehension that extracts vowels from a string.
4. Create a 3×3 matrix using nested lists and print the diagonal elements.
Would you like me to generate a PowerPoint (.pptx) or PDF version of this lecture for
classroom presentation?
You said:
Excellent — let’s look at how to take input into a nested list (like a 2D matrix) in
Python.
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
58
✅ Method 1: Manual Row Input
rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))
matrix = []
for i in range(rows):
row = []
for j in range(cols):
val = int(input(f"Enter element [{i}][{j}]: "))
[Link](val)
[Link](row)
print("Matrix:")
for r in matrix:
print(r)
Explanation:
for i in range(rows):
row = list(map(int, input(f"Enter elements of row {i+1} separated
by space: ").split()))
[Link](row)
print("Matrix:", matrix)
Example Input:
Output:
59
✅ Method 3: One-line List Comprehension
Example input:
Output:
⚙ Accessing Elements
Would you like me to show the same concept extended to 3D list input (like tensor
input) next?
You said:
Perfect 👍 — let’s see how to take input into a 3×4 matrix (3 rows, 4 columns) in
Python.
60
row = list(map(int, input(f"Enter 4 elements for row {i+1},
separated by space: ").split()))
[Link](row)
print("3x4 Matrix:")
for r in matrix:
print(r)
Example Input
Output
3x4 Matrix:
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]
Input:
1 2 3 4
5 6 7 8
9 10 11 12
Output:
✅ Accessing Elements
print(matrix[0][2]) # element from 1st row, 3rd column → 3
Would you like me to extend this example to show matrix addition or multiplication
using the same 3×4 input format?
You said:
61
program to multiply 2x3 and 3x4
ChatGPT said:
Excellent — let’s write a full Python program that takes input for a 2×3 and a 3×4
matrix, and then multiplies them to produce a 2×4 result matrix.
# Matrix multiplication
for i in range(2): # rows of A
for j in range(4): # columns of B
for k in range(3): # common dimension
result[i][j] += A[i][k] * B[k][j]
Example Input
Enter elements for the first matrix (2x3):
1 2 3
4 5 6
Enter elements for the second matrix (3x4):
7 8 9 10
11 12 13 14
15 16 17 18
Output
Resultant Matrix (2x4):
[74, 80, 86, 92]
[173, 188, 203, 218]
62
⚙ Explanation
A→ 2×3 matrix
B→ 3×4 matrix
Result C → 2×4 matrix
Formula:
Would you like me to show how to implement the same program using NumPy, so that
it handles any matrix sizes automatically?
You said:
Sure 👍 — here are some well-structured exercises on Python Lists ranging from basic
to slightly advanced, perfect for class practice or assignments.
63
🔹 Level 2: Intermediate
Sort a list of numbers in ascending and descending order without using sort()
(hint: use loops).
13. Multiples of 3
Take a 3×3 matrix (nested list) as input and print its diagonal elements.
64
Add two 2×2 matrices using nested loops.
🔹 Challenge Problems
Given a list with repeated elements, create a new list with only unique elements
(no sets).
Would you like me to prepare solutions or hints for these exercises next (e.g., for
classroom handouts)?
You said:
Here’s a clear and complete list of Python data structures, organized by category 👇
65
1. Built-in Data Structures
These are available directly in Python without importing any module.
66
3. Specialized Data Structures (External Libraries)
Library Data Structure Purpose
NumPy ndarray Fast multidimensional arrays
Pandas Series, DataFrame Tabular & labeled data
NetworkX Graph, DiGraph Graphs and networks
[Link] Priority Queue Thread-safe priority structure
Would you like me to prepare a summary table comparing operations and complexity
(like time complexity for insert, search, delete for each built-in structure)? It’s often very
useful for teaching or quick reference.
67
Chapter 10: Python Sets
🎯 Learning Objectives
By the end of this lecture, you will be able to:
1. What is a Set?
A set is a collection of unique and unordered elements.
Example:
# Creating a set
fruits = {'apple', 'banana', 'mango', 'apple'} # 'apple' appears twice
print(fruits) # Output: {'apple', 'banana', 'mango'}
⚠ Empty Set
68
empty_set = set() # ✅ Correct
empty_dict = {} # ⚠ This creates an empty dictionary
🔧 4. Modifying Sets
➕ Add elements
[Link]('orange')
➖ Remove elements
[Link]('banana') # Removes 'banana', raises error if not found
[Link]('kiwi') # No error if 'kiwi' not found
69
⚖5. Set Operations
Let’s consider:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
Operation Symbol / Method Example Result
Union ` orunion()` `A
Intersection & or intersection() A & B {3,4}
Difference - or difference() A - B {1,2}
Symmetric Difference ^ or symmetric_difference() A ^ B {1,2,5,6}
🔍 6. Set Membership
if 3 in A:
print("3 is in A")
if 7 not in A:
print("7 is not in A")
A = frozenset([1, 2, 3])
# [Link](4) # ❌ Error: cannot modify frozenset
📘 8. Example Program
# Demonstrating set operations
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print("A ∪ B =", A | B)
print("A ∩ B =", A & B)
print("A - B =", A - B)
print("A Δ B =", A ^ B)
Output:
A ∪ B = {1, 2, 3, 4, 5, 6}
A ∩ B = {3, 4}
70
A - B = {1, 2}
A Δ B = {1, 2, 5, 6}
💡 9. Key Properties
Property Description
Unordered Elements have no fixed order
Unique No duplicates allowed
Mutable You can add/remove items
Iterable You can loop through it
Not Indexable No indexing or slicing
Exercise 1
Create a set of numbers 1–10. Remove even numbers.
✅ Solution:
# Create a set from 1 to 10
numbers = set(range(1, 11))
71
Output:
Set after removing even numbers: {1, 3, 5, 7, 9}
Exercise 2
Find the common students between two courses using sets.
✅ Solution:
course_A = {"Rahim", "Karim", "Salma", "Anis"}
course_B = {"Salma", "Anis", "Borna", "Tuhin"}
Output:
Common students: {'Salma', 'Anis'}
Exercise 3
Create two sets and find: Union, Intersection, Symmetric Difference
✅ Solution:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
union_set = A | B
intersection_set = A & B
sym_diff_set = A ^ B
print("Union:", union_set)
print("Intersection:", intersection_set)
print("Symmetric Difference:", sym_diff_set)
Output:
Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
Symmetric Difference: {1, 2, 5, 6}
72
Exercise 4
Find unique characters in a word using a set.
✅ Solution:
word = "mississippi"
unique_chars = set(word)
print("Unique characters:", unique_chars)
Output:
Unique characters: {'p', 'i', 'm', 's'}
💡 Bonus Challenge
Write a program that takes two sentences and finds all the unique words that appear in
either one but not both.
✅ Solution:
s1 = "I love Python programming"
s2 = "Python programming is fun"
set1 = set([Link]().split())
set2 = set([Link]().split())
Output:
Words unique to each sentence: {'i', 'fun', 'love', 'is'}
73
Chapter 11: Python Tuples
1. Introduction to Tuples
📘 Definition
# Example
numbers = (10, 20, 30, 40)
print(numbers)
Output:
Key Properties
Property Description
Ordered Elements maintain their position
Immutable Cannot be changed after creation
Allows duplicates Same value can appear multiple times
Can contain mixed data types e.g., integers, strings, lists, etc.
2. Creating Tuples
74
2.4 Tuple with One Element
Add a comma after the first element, otherwise Python treats it as a value, not a tuple.
single = (5,)
print(type(single)) # <class 'tuple'>
Slicing Tuples
print(colors[1:3]) # ('green', 'blue')
print(colors[:2]) # ('red', 'green')
print(colors[::2]) # ('red', 'blue')
🔄 4. Tuple Operations
Operation Example Result
Concatenation (1, 2) + (3, 4) (1, 2, 3, 4)
Repetition (1, 2) * 3 (1, 2, 1, 2, 1, 2)
Membership 3 in (1, 2, 3) True
Length len((1, 2, 3)) 3
Built-in Functions
numbers = (3, 1, 4, 1, 5, 9)
print(len(numbers)) # 6
print(max(numbers)) # 9
print(min(numbers)) # 1
print(sum(numbers)) # 23
print(sorted(numbers)) # [1, 1, 3, 4, 5, 9]
75
Tuple Methods
t = (1, 2, 3, 2, 4)
print([Link](2)) # 2
print([Link](3)) # 2
Packing
Unpacking
a, *b = (1, 2, 3, 4)
print(a) # 1
print(b) # [2, 3, 4]
⚙ 7. Immutability of Tuples
t = (1, 2, 3)
t[0] = 5 # ❌ Error: 'tuple' object does not support item assignment
However, if a tuple contains a mutable element (like a list), that list can be changed:
76
8. Tuples vs Lists
Feature Tuple List
Syntax () []
Mutability Immutable Mutable
Methods Few (2) Many
Performance Faster Slower
Use case Fixed data Dynamic data
Example:
import sys
tuple_size = [Link]((1, 2, 3))
list_size = [Link]([1, 2, 3])
print(tuple_size, list_size)
coordinates = {}
coordinates[(23.7, 90.4)] = "Dhaka"
print(coordinates)
There is no tuple comprehension, but you can create tuples using a generator
expression:
77
Example 2: Returning Multiple Values from a Function
def min_max(numbers):
return min(numbers), max(numbers)
13. Exercises
🔹 Exercise 1:
🔹 Exercise 2:
🔹 Exercise 3:
Given:
t = (1, 2, 3, 4, 5)
🔹 Exercise 4:
Write a function that takes a tuple of student names and returns a tuple of names that start
with 'A'.
14. Summary
Concept Key Point
Tuple Immutable sequence
Creation () or comma-separated values
Access Indexing, slicing
Operations +, *, in, len()
78
Methods .count(), .index()
Use case When data should not change
Advantages Fast, memory efficient, hashable
79
Chapter 12: Dictionaries in Python
Duration: 2–3 Hours
Target Audience: 1st/2nd year undergraduate students (non-CS background)
Prerequisite: Basic understanding of Python variables, lists, and loops
🎯 Learning Objectives
Chapter Outline
Time Topic
80
🔹 1. Introduction to Dictionaries (20 minutes)
What is a Dictionary?
Syntax:
Example:
Key Characteristics:
Keys must be unique and immutable (can’t be changed)
→ e.g., strings, numbers, or tuples
Values can be any type (int, str, list, another dict, etc.)
Dictionaries are unordered (before Python 3.7) but insertion-ordered (since
Python 3.7+).
Mutable — can be modified after creation.
Creating Dictionaries
81
data = {} data["id"] = 1001 data["name"] = "Reza"
Accessing Elements
Example Program 1
employee = { "id": 101, "name": "Selim", "designation": "Engineer" }
print("Employee ID:", employee["id"])
print("Name:", [Link]("name"))
print("Department:", [Link]("department", "Not assigned"))
Removing Items
[Link]("city") # removes 'city' key
del person["email"] # removes 'email' key
[Link]() # removes all items
Output:
82
{'Alice': 88, 'Charlie': 90, 'David': 85}
[Link]({"country":
[Link]() Adds/updates multiple pairs "Bangladesh"})
83
print(key)
Output:
Example:
84
🔹 7. Practical Examples & Exercises (30–45 minutes)
Exercises
Part A – Basic
1. Create a dictionary person with keys: name, age, city. Print each key and value.
2. Add a new key profession and update the city.
3. Remove the age key and print the final dictionary.
Part B – Intermediate
4. Write a program to count frequency of each letter in a given string.
5. Create a dictionary of 5 students and their scores. Print only those who scored
above 80.
6. Merge two dictionaries into one.
Part C – Advanced
7. Create a nested dictionary for 3 employees (id, name, salary).
Then print only names of employees earning above 50,000.
8. Build a small “Library System” using a dictionary —
where each book’s title is a key, and details (author, copies, price) are stored in a
nested dictionary.
85
Review Questions
1. What are the key differences between a list and a dictionary?
2. Can dictionary keys be mutable types? Why or why not?
3. How does the get() method differ from direct key access?
4. What happens if two items have the same key?
5. Explain how you can loop through both keys and values simultaneously.
🏁 Summary
Dictionaries store key-value pairs and provide fast lookups.
Keys must be unique and immutable, values can be any data type.
You can easily add, update, delete, and iterate through elements.
Nested dictionaries allow representing complex data structures.
Widely used in real-world Python applications — from databases to APIs.
86
Chapter 13: Python List Vs Tuple Vs Set Vs Dictionary
1. Overview
Data Type Syntax Example Description
List [1, 2, 3] Ordered, mutable collection of elements
Tuple (1, 2, 3) Ordered, immutable collection
Set {1, 2, 3} Unordered collection of unique elements
Dictionary {'a': 1, 'b': 2} Unordered collection of key-value pairs
⚙ 2. Similarities
Feature Lists Tuples Sets Dictionaries
Can store multiple items ✅ ✅ ✅ ✅
Can store different data types ✅ ✅ ✅ ✅
Can be iterated (looped through) ✅ ✅ ✅ ✅
Can be nested (contain another list/tuple/set/dict) ✅ ✅ ✅ ✅
Support membership test (in) ✅ ✅ ✅ ✅
Support built-in functions (len(), max(), min(), ✅ ✅ ✅ ✅ (for keys)
etc.)
Can be converted to/from other sequence types ✅ ✅ ✅ ✅
So — all four are Python collections, but they differ in mutability, ordering, and
internal structure.
🔍 3. Key Differences
🔹 (A) Mutability
Type Mutable? Example
List ✅ Yes You can add, remove, or modify items
Tuple ❌ No Once created, elements cannot be changed
Set ✅ Yes You can add/remove elements, but no duplicates
Dictionary ✅ Yes Keys and values can be added/updated/removed
Example:
lst = [1, 2, 3]
[Link](4) # Works
tup = (1, 2, 3)
# tup[0] = 10 # ❌ Error
st = {1, 2, 3}
[Link](4) # Works
87
d = {'a': 1, 'b': 2}
d['c'] = 3 # Works
🔹 (B) Ordering
Type Ordered? (Python 3.7+)
List ✅ Yes
Tuple ✅ Yes
Set ❌ No
Dictionary ✅ Yes (maintains insertion order)
🔹 (D) Duplicates
Type Allows Duplicates?
List ✅ Yes
Tuple ✅ Yes
Set ❌ No
Dictionary ❌ (keys must be unique; values can repeat)
88
List Dynamic collections, frequent updates
Tuple Fixed data, function returns, as dictionary keys
Set Removing duplicates, mathematical set operations
Dictionary Storing key-value data, fast lookups
Example:
import sys
lst = [1, 2, 3]
tup = (1, 2, 3)
print([Link](lst), [Link](tup)) # tuple uses less memory
5. Example Comparison
# List
fruits = ['apple', 'banana', 'cherry']
# Tuple
coordinates = (23.7, 90.4)
# Set
unique_numbers = {1, 2, 2, 3}
print(unique_numbers) # {1, 2, 3}
# Dictionary
student = {'name': 'Alice', 'age': 21}
print(student['name'])
6. Summary Table
Feature List Tuple Set Dictionary
Ordered ✅ ✅ ❌ ✅
Mutable ✅ ❌ ✅ ✅
Indexed ✅ ✅ ❌ ❌
Duplicates ✅ ✅ ❌ ❌ (keys only)
Allowed
Syntax [] () {} {'key': value}
Type of Any Any Unique Key-Value pairs
Elements
Access Type Index Index Iteration Key
Hashable ❌ ✅ (if elements are ❌ Keys must be
89
immutable) hashable
Common append(), count(), index() add(), union(), keys(), values(),
Methods pop(), sort() intersection() items()
Common Use Dynamic list Fixed data Unique Key–value mapping
collection
Example 1: Mutability
# List can change
lst = [1, 2, 3]
[Link](4)
# Tuple cannot
tup = (1, 2, 3)
# [Link](4) # ❌ Error
90