0% found this document useful (0 votes)
32 views98 pages

Tiny Book On Python by ChatGPT Edited by MRS

This document is a comprehensive guide on Python programming aimed at first and second-year university students, particularly those without a computer science background. It covers essential topics such as variables, data types, operators, control flow, loops, functions, and data structures, with explanations, examples, and exercises throughout. The book is authored by ChatGPT 5.0 and edited by Dr. Mohammad Reza Selim, and is designed to facilitate learning Python in a structured manner.

Uploaded by

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

Tiny Book On Python by ChatGPT Edited by MRS

This document is a comprehensive guide on Python programming aimed at first and second-year university students, particularly those without a computer science background. It covers essential topics such as variables, data types, operators, control flow, loops, functions, and data structures, with explanations, examples, and exercises throughout. The book is authored by ChatGPT 5.0 and edited by Dr. Mohammad Reza Selim, and is designed to facilitate learning Python in a structured manner.

Uploaded by

clashofking.akd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

A Tiny Book on

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

Dr. Mohammad Reza Selim


Professor
Dept. of Computer Science and Engineering
Shahjalal University of Science and Technology
Sylhet-3114, Bangladesh

October 2025

i
Table of contents

Chapter 1: Introduction to Python 1

Chapter 2: Variables and Data Types in Python 4


2.1 Introduction 4

2.2 What is a Variable? 4

2.3 Understanding Data Types 5

2.4 Numbers in Python 5

2.5 Strings 6

2.6 Boolean Type 6

2.7 Type Conversion (Casting) 6

2.8 Getting Input from User 7

2.9 Constants 7

2.10 Example Programs 7

2.11 Exercises 8

2.12 Summary 9

Chapter 3: Operators and Expressions 10


🎯 Learning Objectives 10

🕐 Lecture Outline 10

🔹 1. Introduction to Operators and Expressions (20 minutes) 11

🔹 2. Arithmetic Operators (40 minutes) 11

🔹 3. Comparison (Relational) Operators (25 minutes) 12

🔹 4. Assignment Operators (25 minutes) 12

🔹 5. Logical Operators (30 minutes) 13

ii
🔹 6. Bitwise Operators (30 minutes) 13

🔹 7. Identity Operators (15 minutes) 14

🔹 8. Membership Operators (15 minutes) 14

🔹 9. Operator Precedence and Associativity (30 minutes) 15

🔹 10. Expressions and Evaluation (30 minutes) 15

🔹 11. Practical Examples (30 minutes) 16

Exercises 16

Review Questions 17

🏁 Summary 17

Chapter 4: Input and Output in Python 18

1. Introduction 18

2. Input in Python 18

3. Output in Python 20

4. Input and Output Together (Small Programs) 21

5. Output Formatting for Tables 22

6. File Input and Output (Preview) 22

7. Summary 22

8. Exercises 22

Chapter 5: Conditional Statements in Python 24


1. Introduction 24

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

7. The if-elif-else Ladder 25

8. Nested if Statements 26

9. The pass Statement 26

10. Conditional Expressions (Ternary Operator) 27

11. Combining Conditions 27

12. Comparing Strings 27

13. Practical Example Programs 27

14. Common Mistakes 29

15. Summary 29

16. Exercises 29

17. Suggested Lab Tasks 30

18. Extension Topics (Optional) 30

Chapter 6: Loops in Python 31


1. Introduction: Why Loops? 31

2. Types of Loops in Python 31

3. The for Loop 31

4. The while Loop 33

5. break, continue, and pass Statements 34

6. else with Loops 35

7. Nested Loops (Loop inside a loop) 35

8. Infinite Loops 36

9. Practical Example Programs 36

10. Common Mistakes 37

11. Summary Table 37

iv
12. Exercises (Gradually Increasing Difficulty) 37

13. Lab Tasks 38

14. Summary 39

Chapter 7: Functions in Python 40


1. Introduction 40

2. Types of Functions 40

3. Defining a Function 40

4. Function Parameters and Arguments 41

5. Return Statement 41

6. Types of Arguments 41

7. Scope and Lifetime of Variables 42

8. Function Returning Multiple Values 43

9. Lambda (Anonymous) Functions 43

10. Recursion 43

11. Functions in Modules 44

12. Practical Example Programs 44

13. Exercises 45

14. Summary 46

Chapter 8: Strings 47
🎯 Learning Objectives 47

🕐 Lecture Outline 47

🔹 1. Introduction to Strings (20 minutes) 48

🔹 2. Creating and Accessing Strings (25 minutes) 48

🔹 3. String Operations (30 minutes) 49

v
🔹 4. String Methods (30 minutes) 50

🔹 5. String Formatting (30 minutes) 51

🔹 6. Escape Sequences & Multiline Strings (25 minutes) 52

🔹 7. Practical Examples & Exercises (30–40 minutes) 52

Exercises 54

Review Questions 54

🏁 Summary 54

Chapter 9: Python Lists 55

Taking Input into a Nested List (2D List) 58

Taking Input into a 3×4 Matrix 60

Matrix Multiplication Program (2×3 × 3×4 → 2×4) 62

Exercises on Python Lists 63

1. Built-in Data Structures 66

2. Advanced / Derived Data Structures (from modules) 66

3. Specialized Data Structures (External Libraries) 67

⚙4. Custom Data Structures (Implemented via Classes) 67

Chapter 10: Python Sets 68


🎯 Learning Objectives 68

1. What is a Set? 68

⚙2. Creating a Set 68

✍ 3. Accessing Set Elements 69

🔧 4. Modifying Sets 69

⚖5. Set Operations 70

🔍 6. Set Membership 70

vi
🔗 7. Frozen Set (Immutable Set) 70

📘 8. Example Program 70

💡 9. Key Properties 71

10. Small Exercises 71

Exercise 1 71

Exercise 2 72

Exercise 3 72

Exercise 4 73

💡 Bonus Challenge 73

Chapter 11: Python Tuples 74


1. Introduction to Tuples 74

2. Creating Tuples 74

🔍 3. Accessing Tuple Elements 75

🔄 4. Tuple Operations 75

5. Tuple Functions and Methods 75

6. Tuple Packing and Unpacking 76

⚙ 7. Immutability of Tuples 76

8. Tuples vs Lists 77

💡 9. Tuples as Dictionary Keys 77

10. Nested Tuples and Iteration 77

11. Tuple Comprehension? 77

12. Practical Examples 77

13. Exercises 78

14. Summary 78

vii
Chapter 12: Dictionaries in Python 80
🎯 Learning Objectives 80

Chapter Outline 80

🔹 1. Introduction to Dictionaries (20 minutes) 81

🔹 2. Creating and Accessing Dictionaries (30 minutes) 81

🔹 3. Modifying Dictionaries (30 minutes) 82

🔹 5. Looping Through Dictionaries (30 minutes) 83

🔹 6. Nested Dictionaries (25 minutes) 84

🔹 7. Practical Examples & Exercises (30–45 minutes) 85

Exercises 85

Review Questions 86

🏁 Summary 86

Chapter 13: Python List Vs Tuple Vs Set Vs Dictionary 87


1. Overview 87

⚙ 2. Similarities 87

🔍 3. Key Differences 87

⚙ 4. Performance and Memory 89

5. Example Comparison 89

6. Summary Table 89

7. Quick Examples to Show Differences 90

8. Choosing the Right Collection 90

✅ 9. Summary in One Line 90

viii
Chapter 1: Introduction to Python
1.1 What is Python?

Python is a high-level, interpreted, general-purpose programming language.


It was created by Guido van Rossum in 1991 and is maintained by the Python Software
Foundation (PSF).

Python emphasizes readability, simplicity, and flexibility, which makes it ideal for
beginners as well as professionals.

1.2 Key Features of Python


Feature Description
Easy to Learn Simple syntax similar to English.
Interpreted No need to compile; executed line by line.
Dynamically Typed No need to declare variable types explicitly.
Portable Runs on Windows, Linux, macOS, etc.
Extensible Can integrate with C/C++ and Java code.
Rich Library Support Includes modules for almost any task (math, data, web, etc.).
Open Source Freely available for anyone to use.

1.3 Where is Python Used?

Python is widely used in:

 Data Science & Machine Learning (e.g., NumPy, pandas, TensorFlow)


 Web Development (e.g., Django, Flask)
 Automation/Scripting
 Game Development
 Cyber Security
 Bioinformatics
 IoT & Robotics

1.4 Python Versions

 Python 2.x (Old, no longer maintained)


 Python 3.x (Current version; e.g., 3.12)

To check your version: python --version

1
1.5 Writing and Running Python Programs

Using the Python Shell (Interactive Mode):

>>> print("Hello, World!")


Hello, World!

Using a Script File:

1. Open a text editor or IDE (like IDLE or VS Code).


2. Write your program and save it as [Link]:
3. print("Hello, World!")
4. Run it from the terminal:
5. python [Link]

1.6 Python Syntax Basics

Indentation:
Python uses indentation instead of braces {} to define blocks.

if 5 > 2:
print("Five is greater than two!") # Correct

(A missing or inconsistent indent causes an error.)

Comments:

# This is a single-line comment

"""
This is a
multi-line comment
"""

1.7 Variables and Data Types

You can assign a value to a variable without declaring its type:

x = 10 # int
name = "Alice" # str
pi = 3.1416 # float

1.8 Input and Output


name = input("Enter your name: ")
print("Hello,", name)

2
1.9 Example Program
# Program to calculate area of a circle

radius = float(input("Enter radius: "))


area = 3.1416 * radius * radius
print("Area =", area)

Output:

Enter radius: 5
Area = 78.54

1.10 Advantages and Limitations of Python

Advantages:

 Easy to read and write


 Large community support
 Huge library ecosystem
 Cross-platform

Limitations:

 Slower than compiled languages like C++


 Not ideal for mobile development
 High memory usage in large data processes

1.11 Exercise

1. Write a program to print your name and department.


2. Write a program to add two numbers entered by the user.
3. Write a program to convert temperature from Celsius to Fahrenheit.
4. Run your programs using both IDLE and command prompt.

1.12 Summary

 Python is an interpreted, high-level, general-purpose language.


 Focuses on readability and simplicity.
 Used in many fields including AI, web, and bioinformatics.
 Basic syntax includes indentation, comments, and variables.
 Easy for beginners to start coding immediately.

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.

2.2 What is a Variable?

A variable is a name that refers to a value stored in memory.

It acts as a container to hold data that can be used and modified later.

Example:

x = 10
y = 3.5
name = "Alice"

Here:

 x stores an integer (10)


 y stores a float (3.5)
 name stores a string ("Alice")

2.2.1 Variable Naming Rules

1. A variable name must begin with a letter or underscore (_).


2. It cannot start with a number.
3. It can contain only letters, numbers, and underscores.
4. Variable names are case-sensitive (Age ≠ age).
5. Reserved words (keywords) cannot be used as variable names.

✅Valid:
name, _value, age2, student_name

❌Invalid:
2name, student name, class

4
2.2.2 Multiple Assignments

Python allows multiple variables to be assigned in a single line.

a, b, c = 10, 20, 30
print(a, b, c)

x = y = z = 5
print(x, y, z)

2.3 Understanding Data Types

A data type defines the kind of value a variable holds and what operations can be
performed on it.

2.3.1 Basic Built-in Data Types


Data Type Description Example
int Integer numbers x = 10
float Decimal numbers pi = 3.1416
str String (sequence of characters) "Hello"
bool Boolean (True/False) x = True
complex Complex numbers z = 2 + 3j

2.3.2 Checking Type

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

2.4 Numbers in Python

Python supports three types of numbers:

1. int — whole numbers


2. float — real numbers with decimal points

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

2.6 Boolean Type

Booleans represent True or False values.

They are often used in conditional statements.

x = True
y = False
print(x and y) # False
print(x or y) # True

2.7 Type Conversion (Casting)

You can convert between types using casting functions.

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.8 Getting Input from User

The input() function reads a string from the user.

name = input("Enter your name: ")


age = input("Enter your age: ")
print("Hello", name, "you are", age, "years old.")

Type Casting with Input:

a = int(input("Enter number 1: "))


b = int(input("Enter number 2: "))
sum = a + b
print("Sum =", sum)

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

2.10 Example Programs

Example 1: Calculate Average of Three Numbers


a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
c = float(input("Enter third number: "))

7
average = (a + b + c) / 3
print("Average =", average)

Example 2: Simple Interest Calculator


p = float(input("Enter Principal: "))
r = float(input("Enter Rate of Interest: "))
t = float(input("Enter Time in years: "))

si = (p * r * t) / 100
print("Simple Interest =", si)

Example 3: Convert Days into Years, Weeks, and Days


days = int(input("Enter number of days: "))
years = days // 365
weeks = (days % 365) // 7
remaining_days = (days % 365) % 7

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?

Part B: Coding Practice

1. Write a program to find the square and cube of a number.


2. Write a program to convert temperature from Fahrenheit to Celsius.
3. Write a program to calculate the area and perimeter of a rectangle.
4. Write a program to swap two variables using a temporary variable and without
using one.
5. Write a program that takes your birth year and prints your age.

8
2.12 Summary

 Variables are names used to store data values.


 Python is dynamically typed — no need for explicit declaration.
 Basic data types: int, float, str, bool, complex.
 type() is used to check variable type.
 Use input() for user input and cast to int() or float() when needed.
 Constants are written in uppercase by convention.

9
Chapter 3: Operators and Expressions

Duration: 2–4 Hours


Target Audience: 1st/2nd Year Undergraduate Students (Non-CS Background)
Prerequisites:

 Basic knowledge of Python syntax


 Familiarity with data types (numbers, strings, booleans)

🎯 Learning Objectives

By the end of this lecture, students will be able to:

1. Understand what operators and expressions are.


2. Identify different types of Python operators.
3. Use arithmetic, comparison, logical, assignment, bitwise, and membership
operators.
4. Understand operator precedence and associativity.
5. Write and evaluate complex expressions.
6. Solve small real-world problems using operators.

🕐 Lecture Outline
Time Topic

0:00 – 0:20 Introduction to Operators and Expressions

0:20 – 1:00 Arithmetic, Comparison, and Assignment Operators

1:00 – 1:45 Logical, Bitwise, and Identity Operators

1:45 – 2:15 Membership Operators

2:15 – 2:45 Operator Precedence and Associativity

2:45 – 3:30 Expressions and Evaluation Examples

3:30 – 4:00 Practical Programs and Exercises

10
🔹 1. Introduction to Operators and Expressions (20 minutes)

What is an Operator?

An operator is a symbol that performs an operation on data (operands).

Example:

a = 10
b = 3
result = a + b # '+' is an operator, a and b are operands

What is an Expression?

An expression is a combination of values, variables, and operators that can be


evaluated to produce a result.

Examples:

3 + 5 * 2
(a + b) / 2
x > 5 and y < 10

🔹 2. Arithmetic Operators (40 minutes)

Arithmetic operators perform basic mathematical operations.

Operator Description Example Output


+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division (float) 10 / 3 3.333...
// Floor Division 10 // 3 3
% Modulus (remainder) 10 % 3 1
** Exponentiation 2 ** 3 8

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)

🔹 3. Comparison (Relational) Operators (25 minutes)

Used to compare two values; result is True or False.

Operator Description Example Output


== 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 <= 4 True

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)

🔹 4. Assignment Operators (25 minutes)

Used to assign values to variables.

Operator Description Example Equivalent To


= Assign x = 5 —
+= Add and assign x += 3 x = x + 3
-= Subtract and assign x -= 2 x = x - 2
*= Multiply and assign x *= 4 x = x * 4
/= Divide and assign x /= 2 x = x / 2
//= Floor divide and assign x //= 3 x = x // 3
%= Modulus and assign x %= 2 x = x % 2
**= Exponent and assign x **= 2 x = x ** 2

12
Example Program 3
x = 10
x += 5
print("After += :", x)
x *= 2
print("After *= :", x)
x -= 4
print("After -= :", x)

🔹 5. Logical Operators (30 minutes)

Used to combine multiple conditions.

Operator Description Example Result


and True if both are True x > 0 and x < 10 True if x is between 0 and
10
or True if at least one is True x < 0 or x > 10 True if x is outside 0–10
not Negates the result not(x > 10) True if x <= 10

Example Program 4
age = 20
country = "Bangladesh"

if age >= 18 and country == "Bangladesh":


print("Eligible to vote.")
else:
print("Not eligible.")

🔹 6. Bitwise Operators (30 minutes)

Used to perform operations on binary numbers (bit-level).

Operator Description Example Result


& AND 5 & 3 1
` ` OR `5
^ XOR 5 ^ 3 6
~ NOT ~5 -6
<< Left shift 5 << 1 10
>> Right shift 5 >> 1 2

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)

🔹 7. Identity Operators (15 minutes)

Used to compare object identity, not equality.

Operator Description Example Result


is True if both refer to same object x is y True/False
is not True if they are different objects x is not y True/False

Example
x = [1, 2, 3]
y = [1, 2, 3]
z = x

print(x == y) # True (same contents)


print(x is y) # False (different objects)
print(x is z) # True (same reference)

🔹 8. Membership Operators (15 minutes)

Used to test whether a value exists in a sequence (string, list, tuple, etc.).

Operator Description Example Result

in True if found 'a' in 'cat' True

not in True if not found 'x' not in 'cat' True

Example
fruits = ["apple", "banana", "mango"]
print("banana" in fruits)
print("orange" not in fruits)

14
🔹 9. Operator Precedence and Associativity (30 minutes)

Operator precedence defines which operator is evaluated first.

Precedence Operators Description


Highest () Parentheses
** Exponentiation
* / // % Multiplication, Division, Floor, Modulus
+ - Addition, Subtraction
<< >> Bitwise shift
& Bitwise AND
^ Bitwise XOR
` `
== != > < >= <= Comparisons
not, and, or Logical Operators
Lowest = Assignment

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

🔹 10. Expressions and Evaluation (30 minutes)

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)

✅ Example 1: Simple Calculator


a = float(input("Enter first number: "))
b = float(input("Enter second number: "))

print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Remainder:", a % b)

✅ Example 2: Discount Calculation


price = float(input("Enter product price: "))
discount = 10 if price > 1000 else 5
final = price - (price * discount / 100)
print(f"Discount = {discount}%, Final Price = {final}")

✅ Example 3: Even or Odd Check using Operators


num = int(input("Enter number: "))
print("Even" if num % 2 == 0 else "Odd")

Exercises

Part A – Basic

1. Evaluate: 5 + 3 * 2, 10 // 3, and (10 + 3) * 2.


2. Write a program to compute area and circumference of a circle.
3. Use assignment operators to update the value of a variable.

Part B – Intermediate

4. Write a program to check if a number is divisible by both 3 and 5.


5. Take two numbers and print which one is larger using comparison operators.
6. Demonstrate all logical operators using examples.

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

1. What is the difference between = and ==?


2. What will be the output of 10 + 2 * 3? Why?
3. Explain the difference between logical and bitwise operators.
4. What are identity operators used for?
5. How does operator precedence affect expression evaluation?

🏁 Summary

 Operators are special symbols that perform computations.


 Expressions combine operators, values, and variables.
 Types: Arithmetic, Relational, Assignment, Logical, Bitwise, Membership,
Identity.
 Operator precedence and associativity decide evaluation order.
 Expressions are the foundation of all computation in Python.

17
Chapter 4: Input and Output in Python

⏱Duration:

2–4 hours (theory + practice)

1. Introduction

Every program needs a way to interact with the user or the outside world.

 Input means taking data from the user or from a file.


 Output means displaying or writing data to the screen or to a file.

In Python:

 input() → takes data from the user (keyboard).


 print() → displays data to the user (screen).

2. Input in Python

2.1 The input() Function

Syntax:

variable = input("Prompt message: ")

 The function displays the prompt message.


 Takes the user’s input from the keyboard.
 Returns it as a string.

Example 1: Basic Input

name = input("Enter your name: ")


print("Hello", name)

Output:

Enter your name: Selim


Hello Selim

18
2.2 Type Conversion (Casting)

The input() function always returns data as a string.


If we need a number, we must convert it:

Conversion Function
Integer int()
Float float()
String str()

Example 2: Taking a Number Input

age = int(input("Enter your age: "))


print("You will be", age + 1, "next year.")

2.3 Multiple Inputs in a Single Line

You can take multiple inputs using split().

Example 3:

a, b = input("Enter two numbers separated by space: ").split()


a = int(a)
b = int(b)
print("Sum:", a + b)

Output:

Enter two numbers separated by space: 5 7


Sum: 12

2.4 Taking Multiple Inputs into a List

Example 4:

numbers = list(map(int, input("Enter numbers separated by space:


").split()))
print("Numbers:", numbers)

Output:

Enter numbers separated by space: 1 2 3 4


Numbers: [1, 2, 3, 4]

19
3. Output in Python

3.1 The print() Function

Syntax:

print(object1, object2, ..., sep=' ', end='\n')

Parameters:

 sep: separator between objects (default: space)


 end: what to print at the end (default: newline)

Example 5:

print("Python", "is", "fun")


print("Python", "is", "fun", sep='-', end='!')

Output:

Python is fun
Python-is-fun!

3.2 Printing Variables and Text Together

Example 6:

name = "Selim"
age = 25
print("Name:", name, ", Age:", age)

3.3 String Formatting Methods

Python provides several ways to format output.

(a) Using + Operator


name = "Alice"
print("Hello " + name)

(b) Using , in print


x = 10
y = 20
print("Sum of", x, "and", y, "is", x + y)

(c) Using [Link]()


name = "Bob"
age = 22
print("My name is {} and I am {} years old.".format(name, age))

20
(d) Using f-Strings (Python 3.6+)
name = "Reza"
marks = 85
print(f"{name} scored {marks} marks.")

3.4 Controlling Decimal Places


pi = 3.14159265
print(f"Pi up to 2 decimal places: {pi:.2f}")

Output:

Pi up to 2 decimal places: 3.14

4. Input and Output Together (Small Programs)

Example 7: Add Two Numbers


a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("Sum =", a + b)

Example 8: Area of a Circle


radius = float(input("Enter radius: "))
area = 3.1416 * radius ** 2
print(f"Area of circle = {area:.2f}")

Example 9: Average of 5 Numbers


numbers = list(map(float, input("Enter 5 numbers separated by space:
").split()))
average = sum(numbers) / len(numbers)
print(f"Average = {average}")

Example 10: Student Grade Report


name = input("Enter student's name: ")
marks = float(input("Enter marks: "))

if marks >= 80:


grade = "A+"
elif marks >= 70:
grade = "A"
elif marks >= 60:
grade = "B"
else:
grade = "F"

print(f"Name: {name}\nMarks: {marks}\nGrade: {grade}")

21
5. Output Formatting for Tables

You can print data neatly using alignment options:

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

6. File Input and Output (Preview)

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

Reading from a File


f = open("[Link]", "r")
content = [Link]()
print(content)
[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:

Write a program to calculate the area of a rectangle (length × width).

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

Create a formatted table showing names and marks of three students.

23
Chapter 5: Conditional Statements in Python

Duration: 4–8 hours (Theory + Practice + Exercises)

1. Introduction

In daily life, we constantly make decisions:

“If it rains, I will take an umbrella. Otherwise, I’ll walk freely.”

Similarly, computers also need to make decisions based on conditions.


Python provides conditional statements that allow programs to execute certain parts of
code only when specific conditions are true.

2. What is a Condition?

A condition is an expression that can be either True or False.

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.

6. The if-else Statement

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

7. The if-elif-else Ladder

When we have multiple conditions, we use elif (“else if”).

Syntax:
if condition1:

25
statements1
elif condition2:
statements2
elif condition3:
statements3
else:
statements_else

Example 3:
marks = int(input("Enter marks: "))

if marks >= 80:


grade = "A+"
elif marks >= 70:
grade = "A"
elif marks >= 60:
grade = "B"
elif marks >= 50:
grade = "C"
else:
grade = "F"

print("Grade:", grade)

8. Nested if Statements

You can place an if inside another if.

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

9. The pass Statement

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)

Short form of if-else in a single line.

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

11. Combining Conditions

You can combine multiple conditions using and, or, not.

Example 7:
age = int(input("Enter age: "))

if age >= 18 and age <= 60:


print("Eligible to work")
else:
print("Not eligible")

12. Comparing Strings

You can also use conditions with strings.

Example 8:
password = input("Enter password: ")
if password == "python123":
print("Access granted")
else:
print("Access denied")

13. Practical Example Programs

Example 9: Find Largest of Three Numbers


a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

27
if a >= b and a >= c:
largest = a
elif b >= a and b >= c:
largest = b
else:
largest = c

print("Largest number:", largest)

Example 10: Check Leap Year


year = int(input("Enter a year: "))

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):


print(year, "is a leap year")
else:
print(year, "is not a leap year")

Example 11: Simple Calculator


a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
op = input("Enter operator (+, -, *, /): ")

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

Example 12: Grading System (Nested Example)


marks = float(input("Enter marks: "))

if marks >= 50:


if marks >= 80:
print("Excellent")
elif marks >= 60:
print("Good")
else:
print("Pass")
else:
print("Fail")

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:

Write a program to check whether a number is positive, negative, or zero.

Exercise 2:

Ask for a person’s age and print:

 “Child” if under 12
 “Teenager” if 13–19
 “Adult” if 20–59
 “Senior” if 60 or above

Exercise 3:

Write a program to find the largest of three numbers.

Exercise 4:

Write a program to check if a given number is divisible by both 3 and 5.

Exercise 5:

Ask a user for their username and password, and grant access only if both are correct.

29
Exercise 6:

Write a program that determines if a year is a leap year.

Exercise 7:

Take a temperature input and classify:

 < 0 → “Freezing”
 0–20 → “Cold”
 21–35 → “Warm”
 35 → “Hot”

Exercise 8 (Challenge):

Create a simple calculator that performs addition, subtraction, multiplication, or division


based on user input.

17. Suggested Lab Tasks

1. Implement a student grading system with GPA output.


2. Build a ticket price calculator with age-based discounts.
3. Simulate a bank login and withdrawal system.
4. Create a weather classifier (Sunny, Rainy, Cold).
5. Write a program to calculate electricity bill using slabs.

18. Extension Topics (Optional)

For advanced understanding:

 Using conditions with lists (if item in list:)


 Conditional expressions inside list comprehensions
 Combining conditions with boolean functions

30
Chapter 6: Loops in Python

Duration: 8–10 Hours (Theory + Practice + Exercises)

1. Introduction: Why Loops?

In daily life, we repeat many tasks:

 Brush teeth every morning


 Send attendance report every day
 Count from 1 to 100

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.

2. Types of Loops in Python

Python supports two main looping constructs:

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:

 nested loops — loops inside loops.


 loop control statements — break, continue, pass.

3. The for Loop

3.1. Basic Syntax


for variable in sequence:
# block of code

 The sequence can be a list, tuple, string, range, etc.


 The variable takes each value from the sequence one by one.

31
3.2. Example 1: Print numbers 1 to 5
for i in range(1, 6):
print(i)

Output:

1
2
3
4
5

3.3. Understanding range()


Function Description Example Output

range(n) 0 → n-1 range(5) 0,1,2,3,4

range(a,b) a → b-1 range(2,6) 2,3,4,5

range(a,b,s) a → b-1 step s range(1,10,2) 1,3,5,7,9

3.4. Example 2: Print even numbers from 2 to 10


for i in range(2, 11, 2):
print(i)

Output:

2
4
6
8
10

3.5. Example 3: Sum of first 10 natural numbers


sum = 0
for i in range(1, 11):
sum += i
print("Sum =", sum)

Output:
Sum = 55

3.6. Example 4: Iterate over a list


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

32
for fruit in fruits:
print(fruit)

Output:

apple
banana
cherry

3.7. Example 5: Iterate over a string


for ch in "Python":
print(ch)

3.8. Example 6: Nested for Loop


for i in range(1, 4):
for j in range(1, 4):
print(f"({i},{j})", end=" ")
print()

Output:

(1,1) (1,2) (1,3)


(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)

3.9. Example 7: Multiplication Table


n = int(input("Enter number: "))
for i in range(1, 11):
print(n, "x", i, "=", n*i)

4. The while Loop

4.1. Basic Syntax


while condition:
# block of code

 The loop repeats as long as the condition is True.


 You must ensure the condition eventually becomes False, otherwise the loop will
run forever!

4.2. Example 1: Print numbers 1 to 5


i = 1
while i <= 5:
print(i)
i += 1

33
4.3. Example 2: Sum of first 10 numbers
i = 1
sum = 0
while i <= 10:
sum += i
i += 1
print("Sum:", sum)

4.4. Example 3: Input until user types “stop”


while True:
word = input("Enter something (or type 'stop'): ")
if word == "stop":
break
print("You entered:", word)

4.5. Example 4: Countdown


n = 5
while n > 0:
print(n)
n -= 1
print("Blast off!")

5. break, continue, and pass Statements

5.1. break — exit the loop immediately


for i in range(1, 10):
if i == 5:
break
print(i)

Output: 1 2 3 4

5.2. continue — skip current iteration


for i in range(1, 10):
if i == 5:
continue
print(i)

Output: 1 2 3 4 6 7 8 9

5.3. pass — do nothing (placeholder)


for i in range(5):

34
pass # To be implemented later

6. else with Loops

Python allows an optional else block with loops.

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

If a break occurs, the else block is skipped.

7. Nested Loops (Loop inside a loop)

Example 1: Pattern Printing


for i in range(1, 6):
for j in range(i):
print("*", end="")
print()

Output:

*
**
***
****
*****

Example 2: Matrix Addition


A = [[1,2,3],
[4,5,6]]
B = [[7,8,9],
[1,2,3]]

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

Press Ctrl+C to stop manually.

Always ensure there’s a termination condition.

9. Practical Example Programs

Example 1: Sum of digits


n = int(input("Enter a number: "))
sum = 0
while n > 0:
digit = n % 10
sum += digit
n //= 10
print("Sum of digits:", sum)

Example 2: Reverse a number


n = int(input("Enter number: "))
rev = 0
while n > 0:
rev = rev*10 + n%10
n //= 10
print("Reversed number:", rev)

Example 3: Factorial of a number


n = int(input("Enter number: "))
fact = 1
for i in range(1, n+1):
fact *= i
print("Factorial =", fact)

Example 4: Fibonacci Series


n = int(input("Enter number of terms: "))
a, b = 0, 1
count = 0

36
while count < n:
print(a)
a, b = b, a + b
count += 1

Example 5: Prime Number Check


n = int(input("Enter number: "))
flag = 0

for i in range(2, n):


if n % i == 0:
flag = 1
break

if flag == 0:
print("Prime number")
else:
print("Not a prime number")

10. Common Mistakes


Mistake Problem Solution
Forgetting i += 1 Infinite loop Always update loop variable
Wrong indentation SyntaxError Indent code correctly
Wrong range end Off-by-one Remember range(a, b) stops before b
errors
Using wrong loop type Logic errors Use for when count known, while when
unknown

11. Summary Table


Type Used When Example
for You know number of iterations Loop over range or list
while Repeat until condition fails Waiting for user input
break Exit loop early Stop at condition
continue Skip one iteration Skip negatives
pass Placeholder Define structure only
else Executes when loop ends normally Post-loop logic

12. Exercises (Gradually Increasing Difficulty)

Beginner

1. Print numbers from 1 to 50 using a loop.


2. Print the square of all numbers from 1 to 10.
3. Print all even numbers between 1 and 100.
4. Find the sum of numbers from 1 to n.

37
5. Display a multiplication table for any number.

Intermediate

6. Count the digits in a number.


7. Print a right-angled triangle pattern of stars.
8. Find the factorial of a number.
9. Reverse a number and check if it’s a palindrome.
10. Calculate the sum of all odd numbers up to n.

Advanced

11. Generate Fibonacci sequence up to n terms.


12. Find all prime numbers between 1 and 100.
13. Create a menu-driven program for basic calculator.
14. Display patterns like:

*****
****
***
**
*

15. Build a simple guessing game:

 The computer picks a random number.


 The user guesses until correct.

13. Lab Tasks

1. Electric Bill Calculation:


Ask user for units consumed and compute total charge based on slabs using loops.
2. Student Marks Entry:
Take input of marks for multiple students, calculate average and highest marks.
3. Simple ATM Simulation:
Allow multiple transactions (deposit, withdraw, balance inquiry) until user quits.
4. Prime Factorization:
Break down a number into its prime factors using loops.

38
14. Summary

Loops help automate repetition, making programs:

 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

A function is a block of reusable code that performs a specific task.


Functions help make programs modular, readable, and easier to debug.

Why use functions?

 To avoid writing the same code repeatedly.


 To divide a large program into smaller manageable parts.
 To make the code more organized and readable.
 To reuse code easily.

2. Types of Functions

1. Built-in functions – already provided by Python (e.g., len(), print(), input(),


type(), range()).
2. User-defined functions – functions created by the programmer.

3. Defining a Function

A function is defined using the def keyword.

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

Calling the function:


greet()

Output:

Hello, welcome to Python!

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, "!")

Calling the function:


greet("Alice")
greet("Rahim")

Output:

Hello Alice !
Hello Rahim !

5. Return Statement

A function can return a value using the return keyword.

Example 3:
def add(a, b):
sum = a + b
return sum

Calling the function:


result = add(10, 5)
print("Sum =", result)

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

Example 4: Default argument


def greet(name="Guest"):
print("Hello", name)

41
Output:

Hello Guest

Example 5: Variable-length arguments


def total(*numbers):
print("Sum =", sum(numbers))

total(2, 3, 5)
total(1, 2, 3, 4, 5)

Output:

Sum = 10
Sum = 15

7. Scope and Lifetime of Variables

 Local variables: defined inside a function, accessible only there.


 Global variables: defined outside all functions, accessible everywhere.

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

Using global keyword


x = 10

def modify():
global x
x = x + 5

modify()
print("After modify:", x)

Output:

42
After modify: 15

8. Function Returning Multiple Values

Example 7:
def calc(a, b):
return a+b, a-b, a*b, a/b

add, sub, mul, div = calc(10, 5)


print("Sum:", add)
print("Difference:", sub)
print("Product:", mul)
print("Quotient:", div)

Output:

Sum: 15
Difference: 5
Product: 50
Quotient: 2.0

9. Lambda (Anonymous) Functions

A lambda function is a short, one-line function without a name.

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

A recursive function calls itself.

43
Example 10: Factorial using recursion
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)

print("Factorial of 5:", factorial(5))

Output:

Factorial of 5: 120

11. Functions in Modules

Functions can be saved in separate files (modules) and reused.

Example:

File: math_utils.py

def add(a, b):


return a + b

Main program:

import math_utils
print(math_utils.add(4, 5))

12. Practical Example Programs

Example 1: Temperature Conversion


def celsius_to_fahrenheit(c):
return (9/5)*c + 32

temp = float(input("Enter temperature in Celsius: "))


print("Temperature in Fahrenheit:", celsius_to_fahrenheit(temp))

Example 2: Find maximum of three numbers


def maximum(a, b, c):
if a >= b and a >= c:
return a
elif b >= a and b >= c:
return b
else:
return c

print("Maximum is:", maximum(3, 9, 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

num = int(input("Enter a number: "))


print("Prime?" , is_prime(num))

13. Exercises

Part A: Basic

1. Write a function to find the square of a number.


2. Create a function that takes two numbers and returns their average.
3. Write a function that prints the first 10 natural numbers.
4. Define a function sum_even(n) that returns the sum of all even numbers up to n.

Part B: Intermediate

5. Write a function to find factorial using recursion.


6. Define a function that checks whether a number is palindrome.
7. Write a function that counts vowels in a string.
8. Create a function that accepts any number of numbers and returns their mean.

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:

 Define and call functions.


 Pass arguments and handle return values.
 Use variable scope and recursion.
 Apply lambda functions.
 Write modular programs.

46
Chapter 8: Strings
Duration: 2–3 Hours
Prerequisite: Basic understanding of Python variables and data types

🎯 Learning Objectives

By the end of this lecture, students will be able to:

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

0:00 – 0:20 Introduction to Strings

0:20 – 0:45 Creating and Accessing Strings

0:45 – 1:15 String Operations and Slicing

1:15 – 1:45 String Methods

1:45 – 2:15 String Formatting

2:15 – 2:40 Escape Sequences and Multiline Strings

47
Time Topic

2:40 – 3:00 Practice Examples and Exercises

🔹 1. Introduction to Strings (20 minutes)

What is a String?

A string is a sequence of characters enclosed in quotes.


Strings can store letters, digits, symbols, or spaces.

Example:

name = "Alice"
message = 'Hello, world!'
info = """This is a multiline string."""

Why Strings Matter


 Used for text data: names, messages, files, etc.
 Strings are immutable → they cannot be changed after creation.
 You can access, copy, and combine them — but not modify individual characters
directly.

String Examples
city = "Dhaka" print(type(city)) # <class 'str'> print(len(city)) # 5

🔹 2. Creating and Accessing Strings (25 minutes)

Creating Strings
s1 = 'Hello'
s2 = "World"
s3 = """This is a multiline string."""

Accessing Characters (Indexing)

Python uses zero-based indexing.

word = "Python"

48
print(word[0]) # P
print(word[3]) # h

Negative indexing (from the end):

print(word[-1]) # n print(word[-2]) # o

Slicing Strings

Extract parts of a string using [start:end]

text = "Bangladesh" print(text[0:6]) # 'Bangla' print(text[6:]) #


'desh' print(text[:3]) # 'Ban'

You can also use a step value:

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

🔹 3. String Operations (30 minutes)

String Concatenation

Joining two or more strings using +

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)

🔹 4. String Methods (30 minutes)

Python provides many built-in string methods.

Method Description Example

upper() Converts to uppercase "hello".upper() → "HELLO"

lower() Converts to lowercase "HELLO".lower() → "hello"

title() Capitalizes each word "python programming".title()

strip() Removes whitespace " hi ".strip()

replace(old, new) Replaces substring "cat".replace("c","r") → "rat"

split() Splits string into list "a,b,c".split(",")

join(list) Joins list into string ",".join(["a","b","c"])

find(sub) Returns index of substring "hello".find("e") → 1

count(sub) Counts occurrences "banana".count("a") → 3

startswith() Checks prefix "hello".startswith("h")

endswith() Checks suffix "[Link]".endswith(".csv")

Example Program 3: Cleaning User Input


name = " Alice "
clean_name = [Link]().upper()
print(clean_name)

50
Output:

ALICE

Example Program 4: Word Counting


sentence = "Python is simple and powerful"
words = [Link]()
print("Total words:", len(words))

🔹 5. String Formatting (30 minutes)

String formatting allows you to insert variables into strings neatly.

Method 1: Using f-strings (Python 3.6+)


name = "Rahim"
age = 20
print(f"My name is {name} and I am {age} years old.")
Method 2: Using format()
print("My name is {} and I am {} years old.".format(name, age))
Method 3: Using % Operator (old style)
print("My name is %s and I am %d years old." % (name, age))

Example Program 5
product = "Laptop"
price = 85000.5
print(f"The price of {product} is {price:.2f} Taka.")

Output:

The price of Laptop is 85000.50 Taka.

51
🔹 6. Escape Sequences & Multiline Strings (25 minutes)

Escape Sequences

Used for special characters inside strings.

Escape Meaning Example

\n Newline "Hello\nWorld"

\t Tab "Name\tAge"

\\ Backslash "C:\\Users"

\' Single quote 'It\'s OK'

\" Double quote "He said \"Hi\""

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)

🔹 7. Practical Examples & Exercises (30–40 minutes)

✅ Example Program 6: Palindrome Checker


word = input("Enter a word: ")
if [Link]() == word[::-1].lower():
print("Palindrome")
else:

52
print("Not a palindrome")

✅ Example Program 7: Count Vowels and Consonants


text = input("Enter text: ")
vowels = "aeiouAEIOU"
vowel_count = sum(1 for ch in text if ch in vowels)
consonant_count = sum(1 for ch in text if [Link]() and ch not in
vowels)
print("Vowels:", vowel_count)
print("Consonants:", consonant_count)

✅ Example Program 8: Email Extractor


data = "Contact us at info@[Link] or support@[Link]" parts =
[Link]() for p in parts: if "@" in p: print("Email found:", p)

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

By the end of this lecture, you will be able to:

 Understand what a list is in Python


 Create and manipulate lists
 Perform common operations like slicing, iteration, and sorting
 Differentiate lists from arrays and other data structures

🔹 1. What is a List?

A list in Python is an ordered, mutable (changeable), and dynamic collection of


elements.
Lists can store different data types — integers, strings, floats, or even other lists.

# Example
my_list = [10, "Hello", 3.14, True]

✅ Ordered → items maintain insertion order


✅ Mutable → you can modify items after creation
✅ Dynamic → you can add or remove items anytime

🔹 2. Creating Lists

There are several ways to create lists:

# Empty list
a = []

# With elements
b = [1, 2, 3, 4]

# Using list() constructor


c = list((5, 6, 7))

# Nested list
d = [[1, 2], [3, 4]]

🔹 3. Accessing Elements

55
Python uses zero-based indexing.

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

print(numbers[0]) # 10
print(numbers[-1]) # 50 (last element)

🔹 4. List Slicing

Extract parts of a list using slice notation [start:end:step].

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


print(numbers[:3]) # [10, 20, 30]
print(numbers[::-1]) # reverse the list

🔹 5. Modifying Lists

Lists are mutable, so you can modify elements:

numbers[2] = 99
[Link](60)
[Link](1, 15)
[Link](99)
del numbers[0]

🔹 6. Common List Methods

Method Description Example


append(x) Add at end [Link](5)
extend(seq) Add multiple items [Link]([6,7])
insert(i,x) Add at position [Link](1,10)
remove(x) Remove first occurrence [Link](10)
pop(i) Remove and return [Link]()
sort() Sort list [Link]()
reverse() Reverse order [Link]()
count(x) Count occurrences [Link](5)
index(x) Find index of element [Link](20)

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

Compact syntax to create lists:

squares = [x**2 for x in range(5)]


even_numbers = [x for x in range(10) if x % 2 == 0]

🔹 9. Copying Lists

Avoid common pitfalls with assignment:

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]

🔹 10. List vs Array

Feature List Array (NumPy)


Data type Mixed Same
Speed Slower Faster (optimized)
Operations General purpose Mathematical
Library Built-in numpy

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:

Taking input into a nested list


ChatGPT said:

Excellent — let’s look at how to take input into a nested list (like a 2D matrix) in
Python.

Taking Input into a Nested List (2D List)


A nested list (list of lists) can be thought of as a table or matrix —
for example:

[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

We’ll go through three different ways to take such input.

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:

 Takes each element individually


 Builds one row at a time
 Appends each row to the matrix

✅ Method 2: Input Whole Row at Once


rows = int(input("Enter number of rows: "))
matrix = []

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:

Enter number of rows: 2


Enter elements of row 1 separated by space: 1 2 3
Enter elements of row 2 separated by space: 4 5 6

Output:

Matrix: [[1, 2, 3], [4, 5, 6]]

59
✅ Method 3: One-line List Comprehension

If you already know the number of rows:

matrix = [list(map(int, input().split())) for _ in


range(int(input("Enter number of rows: ")))]

Example input:

Enter number of rows: 3


1 2 3
4 5 6
7 8 9

Output:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

⚙ Accessing Elements

You can access elements as:

print(matrix[0][1]) # first row, second column

Would you like me to show the same concept extended to 3D list input (like tensor
input) next?

You said:

Take input in a 3x4 matrix


ChatGPT said:

Perfect 👍 — let’s see how to take input into a 3×4 matrix (3 rows, 4 columns) in
Python.

Taking Input into a 3×4 Matrix


✅ Method 1: Row-by-row Input
matrix = []

for i in range(3): # 3 rows

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

Enter 4 elements for row 1, separated by space: 1 2 3 4


Enter 4 elements for row 2, separated by space: 5 6 7 8
Enter 4 elements for row 3, separated by space: 9 10 11 12

Output

3x4 Matrix:
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]

✅ Method 2: One-line List Comprehension

If you want it short and elegant:

matrix = [list(map(int, input().split())) for _ in range(3)]

Input:

1 2 3 4
5 6 7 8
9 10 11 12

Output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

✅ 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 Program (2×3 × 3×4 → 2×4)


# Input for first matrix (2x3)
print("Enter elements for the first matrix (2x3):")
A = [list(map(int, input().split())) for _ in range(2)]

# Input for second matrix (3x4)


print("Enter elements for the second matrix (3x4):")
B = [list(map(int, input().split())) for _ in range(3)]

# Initialize result matrix (2x4) with zeros


result = [[0 for _ in range(4)] for _ in range(2)]

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

# Output the result


print("\nResultant Matrix (2x4):")
for row in result:
print(row)

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:

C[i][j]=∑k=02A[i][k]×B[k][j]C[i][j] = \sum_{k=0}^{2} A[i][k] \times


B[k][j]C[i][j]=k=0∑2A[i][k]×B[k][j]

Would you like me to show how to implement the same program using NumPy, so that
it handles any matrix sizes automatically?

You said:

few exercise on list


ChatGPT said:

Sure 👍 — here are some well-structured exercises on Python Lists ranging from basic
to slightly advanced, perfect for class practice or assignments.

Exercises on Python Lists

🔹 Level 1: Basic Operations

1. List Creation and Access


o Create a list of 5 integers.
o Print the first, middle, and last elements.
2. List Update
o Replace the second element of a list with a new value.
o Add an element to the end using append().
o Insert an element at index 2.
3. List Deletion
o Remove a given value using remove().
o Delete the last element using pop().
4. Length and Membership
5. lst = [3, 7, 9, 12, 15]
o Find the length of the list.
o Check if 12 exists in the list.

63
🔹 Level 2: Intermediate

5. Sum and Average


o Take a list of numbers from the user and find their sum and average.
6. Even and Odd
o From a given list, create two new lists — one containing all even numbers
and the other containing all odd numbers.
7. Reversing a List
o Reverse a list without using the built-in reverse() function.
8. Counting Occurrences
o Count how many times a given element appears in a list.
9. Maximum and Minimum
o Write a program to find the largest and smallest number in a list.
10. Sorting

 Sort a list of numbers in ascending and descending order without using sort()
(hint: use loops).

🔹 Level 3: List Comprehension

11. Squares of Numbers

 Generate a list of squares of numbers from 1 to 10.

12. Filter Vowels

 From a given string, create a list of vowels using list comprehension.

13. Multiples of 3

 Create a list of all numbers between 1 and 50 that are divisible by 3.

🔹 Level 4: Nested Lists

14. Matrix Input

 Take a 3×3 matrix (nested list) as input and print its diagonal elements.

15. Matrix Addition

64
 Add two 2×2 matrices using nested loops.

16. Flatten Nested List

nested = [[1, 2], [3, 4], [5, 6]]

 Convert it into a single flat list [1, 2, 3, 4, 5, 6].

🔹 Challenge Problems

17. Remove Duplicates

 Given a list with repeated elements, create a new list with only unique elements
(no sets).

18. Second Largest Element

 Find the second largest element in a list.

19. Common Elements

 Given two lists, find the elements common to both.

20. List Rotation

 Rotate a list to the right by k positions.

Would you like me to prepare solutions or hints for these exercises next (e.g., for
classroom handouts)?

You said:

list of python data structures


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

Type Description Example


List Ordered, mutable (changeable), allows numbers = [1, 2, 3, 4]
duplicates
Tuple Ordered, immutable, allows duplicates coords = (10, 20, 30)
Set Unordered, unique elements only fruits = {'apple',
'banana', 'mango'}
Dictionary Key–value pairs, unordered (as of Python 3.7 student = {'name':
ordered by insertion) 'Ali', 'age': 22}
String Sequence of characters, immutable text = "Python"

2. Advanced / Derived Data Structures (from modules)


Type Module Description Example
Deque collections Double-ended queue from collections
(fast append/pop from import deque
dq =
both ends) deque([1,2,3])
NamedTuple collections Tuple with named fields from collections
import namedtuple
DefaultDict collections Dictionary with default from collections
values import
defaultdict
OrderedDict collections Dictionary that OrderedDict()
remembers insertion
order (obsolete in 3.7+)
Counter collections Counts occurrences of Counter(['a','b',
elements 'a'])
ChainMap collections Combines multiple dicts ChainMap(d1, d2)
logically
Heap (Priority heapq Min-heap import heapq
Queue) implementation
Queue queue Thread-safe FIFO/LIFO from queue import
queues Queue
Array array Efficient numeric array from array import
(single data type) array
LinkedList — Implemented manually —
(custom) using classes
Stack (custom or — LIFO structure —
via list/deque)
Graph / Tree — Non-linear structures —
(custom or via
networkx, anytree)

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

⚙4. Custom Data Structures (Implemented via Classes)


You can build:

 Stack (using list or deque)


 Queue (using list or deque)
 Linked List (Node-based)
 Binary Tree / BST
 Hash Table
 Graph

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. Understand what a Python set is and why it is used.


2. Create and modify sets.
3. Perform set operations such as union, intersection, and difference.
4. Understand the properties and limitations of sets.

1. What is a Set?
A set is a collection of unique and unordered elements.

 It does not allow duplicates.


 It is mutable (you can add or remove elements).
 But elements inside a set must be immutable (e.g., numbers, strings, tuples —
not lists or dictionaries).

Example:
# Creating a set
fruits = {'apple', 'banana', 'mango', 'apple'} # 'apple' appears twice
print(fruits) # Output: {'apple', 'banana', 'mango'}

➡ Duplicate 'apple' is automatically removed.

⚙2. Creating a Set


a) Using curly braces {}:
numbers = {1, 2, 3, 4}

b) Using set() constructor:


letters = set(['a', 'b', 'c'])

⚠ Empty Set

68
empty_set = set() # ✅ Correct
empty_dict = {} # ⚠ This creates an empty dictionary

✍ 3. Accessing Set Elements


Sets are unordered, so you cannot access elements by index.

You can loop through elements:

for item in fruits:


print(item)

🔧 4. Modifying Sets
➕ Add elements
[Link]('orange')

➕ Add multiple elements


[Link](['grape', 'pineapple'])

➖ Remove elements
[Link]('banana') # Removes 'banana', raises error if not found
[Link]('kiwi') # No error if 'kiwi' not found

Clear all elements


[Link]()

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

🔗 7. Frozen Set (Immutable Set)


A frozenset is an immutable version of a set.
Useful when you want to use a set as a dictionary key or store it in another set.

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

10. Small Exercises


1. Create a set of numbers 1–10. Remove even numbers.
2. Find the common students between two courses using sets.
3. Create two sets and find:
o Union
o Intersection
o Symmetric Difference
4. Write a program to find unique characters in a word using set.
5. word = "mississippi"
6. unique = set(word)
7. print(unique)

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

# Remove even numbers


for n in list(numbers): # convert to list to avoid modifying during
iteration
if n % 2 == 0:
[Link](n)

print("Set after removing even numbers:", numbers)

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"}

common_students = course_A & course_B # intersection


print("Common students:", common_students)

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

unique_words = set1 ^ set2 # symmetric difference


print("Words unique to each sentence:", unique_words)

Output:
Words unique to each sentence: {'i', 'fun', 'love', 'is'}

73
Chapter 11: Python Tuples

Duration: 2–3 hours


Course: Introduction to Programming with Python
Audience: 1st/2nd year university students (non-CS background)

1. Introduction to Tuples

In Python, a tuple is an ordered, immutable collection of elements.


It is similar to a list, but cannot be changed (no adding, removing, or modifying
elements after creation).

📘 Definition

A tuple is created by placing items inside parentheses (), separated by commas.

# Example
numbers = (10, 20, 30, 40)
print(numbers)

Output:

(10, 20, 30, 40)

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

2.1 Empty Tuple


empty_tuple = ()
print(empty_tuple)

2.2 Tuple with Elements


fruits = ("apple", "banana", "cherry")
print(fruits)

2.3 Tuple without Parentheses (Tuple Packing)


t = 1, 2, 3, 4
print(t)

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

2.5 Nested Tuple

Tuples can contain other tuples.

nested = (1, 2, (3, 4), 5)


print(nested)

🔍 3. Accessing Tuple Elements

Tuples are indexed, just like lists.

colors = ("red", "green", "blue", "yellow")


print(colors[0]) # First element
print(colors[-1]) # Last element

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

5. Tuple Functions and Methods

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

Tuples only support two methods:

 count(value) — counts occurrences


 index(value) — returns first index of value

t = (1, 2, 3, 2, 4)
print([Link](2)) # 2
print([Link](3)) # 2

6. Tuple Packing and Unpacking

Packing

Putting multiple values into one tuple.

person = ("Alice", 25, "Dhaka")

Unpacking

Extracting values into separate variables.

name, age, city = person


print(name)
print(age)
print(city)

If you want to unpack part of a tuple:

a, *b = (1, 2, 3, 4)
print(a) # 1
print(b) # [2, 3, 4]

⚙ 7. Immutability of Tuples

Tuples cannot be modified:

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:

t = (1, [2, 3], 4)


t[1][0] = 99
print(t) # (1, [99, 3], 4)

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)

💡 9. Tuples as Dictionary Keys

Because tuples are immutable, they can be used as keys in a dictionary.

coordinates = {}
coordinates[(23.7, 90.4)] = "Dhaka"
print(coordinates)

10. Nested Tuples and Iteration


students = (("Alice", 90), ("Bob", 85), ("Carol", 95))

for name, score in students:


print(f"{name}: {score}")

11. Tuple Comprehension?

There is no tuple comprehension, but you can create tuples using a generator
expression:

t = tuple(x**2 for x in range(5))


print(t)

12. Practical Examples

Example 1: Swapping Variables


a, b = 10, 20
a, b = b, a
print(a, b)

77
Example 2: Returning Multiple Values from a Function
def min_max(numbers):
return min(numbers), max(numbers)

result = min_max([3, 5, 1, 9])


print(result) # (1, 9)
print(type(result)) # tuple

13. Exercises

🔹 Exercise 1:

Create a tuple of 5 countries and:

 Print the first and last country.


 Display the middle 3 countries using slicing.

🔹 Exercise 2:

Write a Python program to:

 Take 5 integers from the user,


 Store them in a tuple,
 Display their sum and average.

🔹 Exercise 3:

Given:

t = (1, 2, 3, 4, 5)

Create a new tuple that contains only even numbers.

🔹 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

By the end of this lecture, students will be able to:

1. Understand what a Python dictionary is and why it’s useful.


2. Create and manipulate dictionaries.
3. Access, add, update, and delete dictionary elements.
4. Use dictionary methods effectively.
5. Iterate through dictionary keys, values, and items.
6. Use nested dictionaries.
7. Apply dictionaries in practical programming problems.

Chapter Outline
Time Topic

0:00 – 0:20 Introduction to Dictionaries

0:20 – 0:50 Creating and Accessing Dictionaries

0:50 – 1:20 Modifying Dictionaries

1:20 – 1:50 Dictionary Methods

1:50 – 2:20 Looping through Dictionaries

2:20 – 2:45 Nested Dictionaries

2:45 – 3:00 Practical Examples & Exercises

80
🔹 1. Introduction to Dictionaries (20 minutes)

What is a Dictionary?

A dictionary in Python is a collection of key-value pairs.


It is used to store data that is related — like a student’s name and ID, or a
product’s name and price.

Syntax:

dictionary_name = { key1: value1, key2: value2, key3: value3 }

Example:

student = { "name": "Alice", "age": 21, "department": "Physics" }

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.

🔹 2. Creating and Accessing Dictionaries (30 minutes)

Creating Dictionaries

Example 1: Using Curly Braces

person = {"name": "John", "age": 30, "city": "Dhaka"}

Example 2: Using dict() Constructor

person = dict(name="John", age=30, city="Dhaka")

Example 3: Empty Dictionary

81
data = {} data["id"] = 1001 data["name"] = "Reza"

Accessing Elements

Use keys to get values:

print(person["name"]) # Output: John print([Link]("age")) # Output:


30

✅ get() is safer — it doesn’t cause an error if the key is missing:

print([Link]("salary", "Not found"))

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

🔹 3. Modifying Dictionaries (30 minutes)

Adding New Key-Value Pair


person["email"] = "john@[Link]"

Updating Existing Value


person["age"] = 31

Removing Items
[Link]("city") # removes 'city' key
del person["email"] # removes 'email' key
[Link]() # removes all items

Example Program 2: Student Database


students = {"Alice": 80, "Bob": 75, "Charlie": 90} # Add a new student
students["David"] = 85 # Update marks
students["Alice"] = 88 # Remove one student
[Link]("Bob")
print(students)

Output:

82
{'Alice': 88, 'Charlie': 90, 'David': 85}

🔹 4. Useful Dictionary Methods (30 minutes)


Method Description Example

[Link]() Returns all keys [Link]()

[Link]() Returns all values [Link]()

[Link]() Returns key-value pairs [Link]()

[Link]({"country":
[Link]() Adds/updates multiple pairs "Bangladesh"})

Removes key and returns its


[Link](key) value [Link]("age")

[Link]() Removes last inserted pair

[Link]() Removes all elements

Example Program 3: Dictionary Methods


student = {"name": "Ayesha", "age": 22, "dept": "CSE"}
print([Link]())
print([Link]())
print([Link]())
[Link]({"year": 4, "age": 23})
print(student)

🔹 5. Looping Through Dictionaries (30 minutes)

Loop through Keys


for key in student:

83
print(key)

Loop through Values


for value in [Link]():
print(value)

Loop through Key–Value Pairs


for key, value in [Link]():
print(key, ":", value)

Example Program 4: Counting Word Frequency


sentence = "python is easy and python is powerful"
words = [Link]()
freq = {}
for word in words:
freq[word] = [Link](word, 0) + 1
print(freq)

Output:

{'python': 2, 'is': 2, 'easy': 1, 'and': 1, 'powerful': 1}

🔹 6. Nested Dictionaries (25 minutes)

A dictionary can contain another dictionary as a value.

Example:

students = { "S101": {"name": "Rahim", "dept": "EEE", "cgpa": 3.75},


"S102": {"name": "Karim", "dept": "CSE", "cgpa": 3.90}, }
print(students["S101"]["name"]) # Output: Rahim

Example Program 5: Display Student Info


for id, info in [Link]():
print("\nStudent ID:", id)
for key, value in [Link]():
print(f"{key}: {value}")

84
🔹 7. Practical Examples & Exercises (30–45 minutes)

✅ Example Program 6: Student Marks Analyzer


marks = { "Alice": {"Math": 85, "English": 78}, "Bob": {"Math": 90,
"English": 88}, "Charlie": {"Math": 70, "English": 75} }
for name, subjects in [Link]():
avg = sum([Link]()) / len(subjects)
print(f"{name}'s Average = {avg}")

✅ Example Program 7: Contact Book


contacts = {}
while True:
name = input("Enter name (or 'exit'): ")
if name == 'exit':
break
phone = input("Enter phone number: ")
contacts[name] = phone
print("\nContact List:")
for name, phone in [Link]():
print(f"{name}: {phone}")

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)

🔹 (C) Indexing and Slicing


Type Supports Indexing? Example
List ✅ lst[1], lst[1:3]
Tuple ✅ tup[-1], tup[:2]
Set ❌ Not allowed
Dictionary ❌ (by position) Access by key: d['a']

🔹 (D) Duplicates
Type Allows Duplicates?
List ✅ Yes
Tuple ✅ Yes
Set ❌ No
Dictionary ❌ (keys must be unique; values can repeat)

🔹 (E) Data Access


Type How You Access Elements
List By index
Tuple By index
Set By iteration only
Dictionary By key

🔹 (F) Syntax Summary


Type Creation Syntax Example
List Square brackets [1, 2, 3]
Tuple Parentheses (1, 2, 3)
Set Curly braces {1, 2, 3}
Dictionary Key–value pairs {'a': 1, 'b': 2}

🔹 (G) Typical Use Cases


Type Typical Use

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

⚙ 4. Performance and Memory


Type Performance Notes
List Slower lookups, fast appends
Tuple Faster and more memory efficient than lists
Set Very fast membership tests (in)
Dictionary Fast key lookups (hash-based)

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

7. Quick Examples to Show Differences

Example 1: Mutability
# List can change
lst = [1, 2, 3]
[Link](4)

# Tuple cannot
tup = (1, 2, 3)
# [Link](4) # ❌ Error

Example 2: Set Removes Duplicates


s = {1, 2, 2, 3}
print(s) # {1, 2, 3}

Example 3: Dictionary Key Lookup


info = {'name': 'Reza', 'age': 35}
print(info['name'])

8. Choosing the Right Collection


Situation Recommended Type
Need to modify elements List
Fixed collection of data Tuple
Need only unique items Set
Need key–value mapping Dictionary

✅ 9. Summary in One Line

List – Ordered + Mutable


Tuple – Ordered + Immutable
Set – Unordered + Unique
Dictionary – Unordered + Key–Value pairs

90

You might also like