Complete Python Learning Course
From Zero to Mastery in Vanilla Python
Welcome to your exciting journey into the world of Python programming! This
course will take you from knowing nothing about programming to becoming a
confident Python programmer. Think of it like learning a new language - but this
language lets you talk to computers!
Table of Contents
Part I: Getting Started (Absolute Beginner)
1. What is Programming and Python?
2. Your First Python Program
3. Variables - Storing Information
4. Basic Data Types
5. Getting Input from Users
Part II: Working with Data (Beginner)
1. Numbers and Math Operations
2. Strings - Working with Text
3. Boolean Logic - True or False
4. Lists - Storing Multiple Items
5. Dictionaries - Storing Key-Value Pairs
Part III: Making Decisions and Loops (Beginner-Intermediate)
1. If Statements - Making Decisions
2. For Loops - Repeating Actions
3. While Loops - Repeating Until Done
4. Break and Continue
Part IV: Organizing Your Code (Intermediate)
1. Functions - Reusable Code Blocks
2. Modules and Packages
3. File Handling - Reading and Writing Files
4. Error Handling - Dealing with Mistakes
Part V: Advanced Data Structures (Intermediate-Advanced)
1. Tuples and Sets
2. List Comprehensions
3. Dictionary and Set Comprehensions
Part VI: Object-Oriented Programming (Advanced)
1. Classes and Objects
2. Inheritance
3. Special Methods (Magic Methods)
Part VII: Advanced Python Features (Advanced)
1. Iterators and Generators
2. Decorators
3. Context Managers
4. Lambda Functions
Part VIII: Standard Library Essentials (Advanced)
1. Important Built-in Functions
2. Working with Dates and Times
3. Regular Expressions
4. JSON and Data Serialization
Part IX: Final Projects and Quiz
1. Practice Projects
2. Final Quiz
1. What is Programming and Python?
What is Programming?
Programming is like giving instructions to a computer. Imagine you're teaching a
friend how to make a sandwich. You need to tell them every step: "Take two slices of
bread, put peanut butter on one slice, put jelly on the other slice, put them together."
Programming is similar - you write step-by-step instructions for a computer to
follow.
What is Python?
Python is a programming language - it's the "language" we use to talk to computers.
It's called Python because its creator liked the British comedy group "Monty Python."
Python is special because: - It's easy to read and write (like English!) - It can do
many different things - Lots of people use it around the world
Why Learn Python?
• It's beginner-friendly
• Used by big companies like Google, Instagram, and Netflix
• Can create websites, games, analyze data, and much more!
2. Your First Python Program
Let's write your very first Python program! In programming, it's traditional to start
with a program that says "Hello, World!"
The print() Function
• What it is: A built-in function that displays text on the screen
• What it's used for: Showing information to the user
• Syntax: print("your message here")
Example:
print("Hello, World!")
When you run this program, it will display: Hello, World!
Try This:
print("Hello, World!")
print("My name is Python!")
print("I'm learning to code!")
Exercise 1: Write a program that prints your name, your age, and your favorite color
on separate lines.
3. Variables - Storing Information
What are Variables?
Variables are like boxes where you can store information. You give the box a name,
and then you can put something inside it and use it later.
Creating Variables
• What it is: A way to store data with a name
• What it's used for: Remembering information to use later
• Syntax: variable_name = value
Examples:
# Simple variables
name = "Alice"
age = 10
height = 4.5
print(name) # Prints: Alice
print(age) # Prints: 10
print(height) # Prints: 4.5
Variable Rules:
• Names can contain letters, numbers, and underscores
• Must start with a letter or underscore (not a number)
• Cannot use special words like print, if, for
• Case sensitive (Name and name are different)
Good Variable Names:
first_name = "John"
student_age = 12
favorite_color = "blue"
Bad Variable Names:
# Don't do this!
1name = "John" # Starts with number
my-name = "John" # Has a dash
print = "John" # Uses special word
Exercise 2: Create variables for your favorite movie, the year it was made, and your
rating out of 10. Then print all three.
4. Basic Data Types
What are Data Types?
Data types tell Python what kind of information you're working with. It's like sorting
things into categories.
1. Strings (Text)
• What it is: Text data
• What it's used for: Storing words, sentences, or any text
• Syntax: Surrounded by quotes "text" or 'text'
name = "Alice"
message = 'Hello there!'
address = "123 Main Street"
2. Integers (Whole Numbers)
• What it is: Whole numbers (positive or negative)
• What it's used for: Counting, ages, scores
• Syntax: Just the number 42
age = 10
score = 95
temperature = -5
3. Floats (Decimal Numbers)
• What it is: Numbers with decimal points
• What it's used for: Measurements, prices, percentages
• Syntax: Number with decimal point 3.14
height = 5.5
price = 19.99
pi = 3.14159
The type() Function
• What it is: Shows you what data type something is
• What it's used for: Checking what type of data you have
• Syntax: type(variable)
name = "Alice"
age = 10
height = 5.5
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
print(type(height)) # <class 'float'>
Exercise 3: Create variables of each type (string, integer, float) and use the type()
function to check each one.
5. Getting Input from Users
The input() Function
• What it is: Gets text from the user
• What it's used for: Making interactive programs
• Syntax: input("question or prompt")
• Returns: Always returns a string
Basic Input:
name = input("What's your name? ")
print("Hello, " + name + "!")
Converting Input to Numbers:
Since input() always gives you text, you need to convert it to numbers:
int() Function
• What it is: Converts text to whole numbers
• What it's used for: When you need to do math with whole numbers
• Syntax: int(text)
age = input("How old are you? ")
age = int(age) # Convert to integer
print("Next year you'll be", age + 1)
float() Function
• What it is: Converts text to decimal numbers
• What it's used for: When you need decimal numbers
• Syntax: float(text)
height = input("How tall are you? ")
height = float(height) # Convert to float
print("That's", height * 12, "inches!")
Shorter Way:
# Get input and convert in one line
age = int(input("How old are you? "))
height = float(input("How tall are you? "))
Exercise 4: Create a program that asks for the user's name and age, then tells them
how old they'll be in 5 years.
6. Numbers and Math Operations
Basic Math Operators
Python can do math just like a calculator!
Addition (+)
result = 5 + 3 # result is 8
print(10 + 15) # Prints: 25
Subtraction (-)
result = 10 - 4 # result is 6
print(20 - 7) # Prints: 13
Multiplication (*)
result = 6 * 7 # result is 42
print(5 * 8) # Prints: 40
Division (/)
result = 15 / 3 # result is 5.0 (always gives float)
print(20 / 4) # Prints: 5.0
Integer Division (//)
• What it is: Division that gives whole numbers only
• What it's used for: When you only want the whole number part
result = 15 // 4 # result is 3 (ignores remainder)
print(20 // 3) # Prints: 6
Modulo (%)
• What it is: Gives the remainder after division
• What it's used for: Finding remainders, checking if numbers are even/odd
result = 15 % 4 # result is 3 (15 ÷ 4 = 3 remainder 3)
print(20 % 3) # Prints: 2
Exponentiation (**)
• What it is: Raises a number to a power
• What it's used for: Calculating squares, cubes, etc.
result = 2 ** 3 # result is 8 (2 × 2 × 2)
print(5 ** 2) # Prints: 25 (5 squared)
Order of Operations
Python follows math rules (PEMDAS): 1. Parentheses 2. Exponents 3. Multiplication
and Division (left to right) 4. Addition and Subtraction (left to right)
result = 2 + 3 * 4 # result is 14 (not 20)
result = (2 + 3) * 4 # result is 20
result = 2 ** 3 + 1 # result is 9 (8 + 1)
Useful Math Functions
abs() Function
• What it is: Gives the absolute value (removes negative sign)
• What it's used for: Finding distances, positive values
print(abs(-5)) # Prints: 5
print(abs(3)) # Prints: 3
round() Function
• What it is: Rounds decimal numbers
• What it's used for: Making numbers simpler
print(round(3.7)) # Prints: 4
print(round(3.2)) # Prints: 3
print(round(3.14159, 2)) # Prints: 3.14 (2 decimal places)
min() and max() Functions
• What they are: Find smallest and largest values
• What they're used for: Comparing numbers
print(min(5, 3, 8, 1)) # Prints: 1
print(max(5, 3, 8, 1)) # Prints: 8
Exercise 5: Create a calculator program that asks for two numbers and shows the
result of all basic operations (+, -, , /, //, %, *).
7. Strings - Working with Text
What are Strings?
Strings are sequences of characters (letters, numbers, symbols). They're like
sentences or words that Python can work with.
Creating Strings
# Single quotes
name = 'Alice'
# Double quotes
message = "Hello, World!"
# Triple quotes for long text
story = """Once upon a time,
there was a young programmer
who loved Python."""
String Concatenation (Joining)
• What it is: Combining strings together
• What it's used for: Building messages, combining text
• Syntax: Use + to join strings
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Prints: John Doe
String Repetition
• What it is: Repeating strings multiple times
• What it's used for: Creating patterns, emphasis
• Syntax: Use * with a number
laugh = "ha" * 3
print(laugh) # Prints: hahaha
print("-" * 20) # Prints: --------------------
String Length
len() Function
• What it is: Counts characters in a string
• What it's used for: Finding how long text is
name = "Alice"
print(len(name)) # Prints: 5
String Indexing
• What it is: Getting individual characters from a string
• What it's used for: Accessing specific letters
• Syntax: string[index] (starts from 0)
name = "Alice"
print(name[0]) # Prints: A (first character)
print(name[1]) # Prints: l
print(name[-1]) # Prints: e (last character)
print(name[-2]) # Prints: c (second to last)
String Slicing
• What it is: Getting parts of a string
• What it's used for: Extracting substrings
• Syntax: string[start:end]
name = "Alice"
print(name[0:3]) # Prints: Ali
print(name[1:4]) # Prints: lic
print(name[:3]) # Prints: Ali (from start)
print(name[2:]) # Prints: ice (to end)
Useful String Methods
.upper() and .lower()
• What they are: Change case of letters
• What they're used for: Formatting text, comparing text
name = "Alice"
print(name.upper()) # Prints: ALICE
print(name.lower()) # Prints: alice
.strip()
• What it is: Removes extra spaces from beginning and end
• What it's used for: Cleaning up user input
messy = " hello "
print(messy.strip()) # Prints: hello
.replace()
• What it is: Replaces parts of a string
• What it's used for: Changing text, fixing typos
sentence = "I love cats"
new_sentence = sentence.replace("cats", "dogs")
print(new_sentence) # Prints: I love dogs
.split()
• What it is: Breaks a string into a list
• What it's used for: Separating words or parts
sentence = "apple,banana,orange"
fruits = sentence.split(",")
print(fruits) # Prints: ['apple', 'banana', 'orange']
.join()
• What it is: Combines a list into a string
• What it's used for: Putting pieces back together
words = ["Hello", "world", "Python"]
sentence = " ".join(words)
print(sentence) # Prints: Hello world Python
String Formatting
f-strings (Modern Way)
• What it is: Easy way to put variables in strings
• What it's used for: Creating formatted messages
• Syntax: f"text {variable} more text"
name = "Alice"
age = 10
message = f"Hello, my name is {name} and I am {age} years old."
print(message)
.format() Method
• What it is: Another way to format strings
• What it's used for: When f-strings aren't available
name = "Alice"
age = 10
message = "Hello, my name is {} and I am {} years old.".format(name, age)
print(message)
Exercise 6: Create a program that asks for a sentence and then: 1. Prints it in
uppercase 2. Prints it in lowercase 3. Prints the number of characters 4. Replaces all
spaces with underscores
8. Boolean Logic - True or False
What are Booleans?
Booleans are data types that can only be True or False. They're like yes/no answers
or on/off switches.
Boolean Values
is_sunny = True
is_raining = False
print(is_sunny) # Prints: True
print(is_raining) # Prints: False
Comparison Operators
These compare values and give back True or False:
Equal to (==)
print(5 == 5) # Prints: True
print(5 == 3) # Prints: False
print("hi" == "hi") # Prints: True
Not equal to (!=)
print(5 != 3) # Prints: True
print(5 != 5) # Prints: False
Greater than (>)
print(7 > 5) # Prints: True
print(3 > 8) # Prints: False
Less than (<)
print(3 < 8) # Prints: True
print(7 < 5) # Prints: False
Greater than or equal to (>=)
print(5 >= 5) # Prints: True
print(7 >= 5) # Prints: True
print(3 >= 8) # Prints: False
Less than or equal to (<=)
print(5 <= 5) # Prints: True
print(3 <= 8) # Prints: True
print(7 <= 5) # Prints: False
Logical Operators
These combine True/False values:
and Operator
• What it is: True only if both sides are True
• What it's used for: Checking multiple conditions
print(True and True) # Prints: True
print(True and False) # Prints: False
print(5 > 3 and 8 > 6) # Prints: True
or Operator
• What it is: True if at least one side is True
• What it's used for: Checking if any condition is met
print(True or False) # Prints: True
print(False or False) # Prints: False
print(5 > 8 or 3 < 6) # Prints: True
not Operator
• What it is: Flips True to False and False to True
• What it's used for: Reversing conditions
print(not True) # Prints: False
print(not False) # Prints: True
print(not 5 > 8) # Prints: True
Truthiness
• What it is: How Python decides if something is True or False
• What it's used for: Understanding what Python considers "truthy" or "falsy"
Falsy Values (Python considers these False):
• False
•0
• 0.0
• "" (empty string)
• [] (empty list)
• {} (empty dictionary)
• None
Truthy Values (Everything else is True):
• True
• Any non-zero number
• Any non-empty string
• Any non-empty list, dictionary, etc.
print(bool(5)) # Prints: True
print(bool(0)) # Prints: False
print(bool("hello")) # Prints: True
print(bool("")) # Prints: False
Exercise 7: Create a program that asks for two numbers and tells the user if: 1. The
first number is greater than the second 2. Both numbers are positive 3. At least one
number is even (hint: use % operator)
9. Lists - Storing Multiple Items
What are Lists?
Lists are like containers that can hold multiple items. Think of them as shopping
lists or collections of things.
Creating Lists
• What it is: A collection of items in order
• What it's used for: Storing multiple related items
• Syntax: [item1, item2, item3]
# Empty list
empty_list = []
# List of numbers
numbers = [1, 2, 3, 4, 5]
# List of strings
fruits = ["apple", "banana", "orange"]
# Mixed types
mixed = [1, "hello", 3.14, True]
Accessing List Items
• What it is: Getting items from specific positions
• What it's used for: Reading data from lists
• Syntax: list[index] (starts from 0)
fruits = ["apple", "banana", "orange"]
print(fruits[0]) # Prints: apple
print(fruits[1]) # Prints: banana
print(fruits[-1]) # Prints: orange (last item)
List Length
fruits = ["apple", "banana", "orange"]
print(len(fruits)) # Prints: 3
Modifying Lists
Adding Items
.append() Method
• What it is: Adds an item to the end of the list
• What it's used for: Growing lists one item at a time
fruits = ["apple", "banana"]
fruits.append("orange")
print(fruits) # Prints: ['apple', 'banana', 'orange']
.insert() Method
• What it is: Adds an item at a specific position
• What it's used for: Inserting items in the middle of lists
fruits = ["apple", "orange"]
fruits.insert(1, "banana") # Insert at position 1
print(fruits) # Prints: ['apple', 'banana', 'orange']
.extend() Method
• What it is: Adds multiple items from another list
• What it's used for: Combining lists
fruits = ["apple", "banana"]
more_fruits = ["orange", "grape"]
fruits.extend(more_fruits)
print(fruits) # Prints: ['apple', 'banana', 'orange', 'grape']
Removing Items
.remove() Method
• What it is: Removes the first occurrence of an item
• What it's used for: Removing specific items
fruits = ["apple", "banana", "orange"]
fruits.remove("banana")
print(fruits) # Prints: ['apple', 'orange']
.pop() Method
• What it is: Removes and returns an item at a specific position
• What it's used for: Taking items out of lists
fruits = ["apple", "banana", "orange"]
removed = fruits.pop(1) # Remove item at index 1
print(removed) # Prints: banana
print(fruits) # Prints: ['apple', 'orange']
del Statement
• What it is: Deletes an item or slice from a list
• What it's used for: Removing items by position
fruits = ["apple", "banana", "orange"]
del fruits[1]
print(fruits) # Prints: ['apple', 'orange']
List Slicing
• What it is: Getting parts of a list
• What it's used for: Extracting sublists
• Syntax: list[start:end]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers[2:5]) # Prints: [3, 4, 5]
print(numbers[:3]) # Prints: [1, 2, 3]
print(numbers[7:]) # Prints: [8, 9, 10]
print(numbers[::2]) # Prints: [1, 3, 5, 7, 9] (every 2nd item)
Useful List Methods
.index() Method
• What it is: Finds the position of an item
• What it's used for: Locating items in lists
fruits = ["apple", "banana", "orange"]
position = fruits.index("banana")
print(position) # Prints: 1
.count() Method
• What it is: Counts how many times an item appears
• What it's used for: Finding duplicates
numbers = [1, 2, 2, 3, 2, 4]
count = numbers.count(2)
print(count) # Prints: 3
.sort() Method
• What it is: Arranges items in order
• What it's used for: Organizing lists
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()
print(numbers) # Prints: [1, 1, 2, 3, 4, 5, 6, 9]
.reverse() Method
• What it is: Reverses the order of items
• What it's used for: Flipping lists
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers) # Prints: [5, 4, 3, 2, 1]
Checking if Items are in Lists
in Operator
• What it is: Checks if an item exists in a list
• What it's used for: Finding if something is present
fruits = ["apple", "banana", "orange"]
print("banana" in fruits) # Prints: True
print("grape" in fruits) # Prints: False
Exercise 8: Create a program that: 1. Starts with an empty list 2. Asks the user to
add 5 favorite movies 3. Prints the complete list 4. Asks which movie to remove and
removes it 5. Prints the final list
10. Dictionaries - Storing Key-Value Pairs
What are Dictionaries?
Dictionaries store information in pairs - like a real dictionary where you look up a
word (key) to find its meaning (value). They're perfect for storing related
information.
Creating Dictionaries
• What it is: A collection of key-value pairs
• What it's used for: Storing related data, like a person's information
• Syntax: {key1: value1, key2: value2}
# Empty dictionary
empty_dict = {}
# Student information
student = {
"name": "Alice",
"age": 10,
"grade": "5th",
"favorite_color": "blue"
}
# Dictionary with numbers as keys
scores = {
1: "Alice",
2: "Bob",
3: "Charlie"
}
Accessing Dictionary Values
• What it is: Getting values using their keys
• What it's used for: Retrieving stored information
• Syntax: dictionary[key]
student = {"name": "Alice", "age": 10, "grade": "5th"}
print(student["name"]) # Prints: Alice
print(student["age"]) # Prints: 10
Adding and Updating Items
student = {"name": "Alice", "age": 10}
# Add new item
student["favorite_color"] = "blue"
# Update existing item
student["age"] = 11
print(student) # Prints: {'name': 'Alice', 'age': 11, 'favorite_color': 'blue'}
Removing Items
del Statement
• What it is: Deletes a key-value pair
• What it's used for: Removing unwanted data
student = {"name": "Alice", "age": 10, "grade": "5th"}
del student["grade"]
print(student) # Prints: {'name': 'Alice', 'age': 10}
.pop() Method
• What it is: Removes and returns a value
• What it's used for: Getting a value while removing it
student = {"name": "Alice", "age": 10, "grade": "5th"}
removed_grade = student.pop("grade")
print(removed_grade) # Prints: 5th
print(student) # Prints: {'name': 'Alice', 'age': 10}
Useful Dictionary Methods
.keys() Method
• What it is: Gets all the keys
• What it's used for: Seeing what keys exist
student = {"name": "Alice", "age": 10, "grade": "5th"}
print(student.keys()) # Prints: dict_keys(['name', 'age', 'grade'])
.values() Method
• What it is: Gets all the values
• What it's used for: Seeing what values exist
student = {"name": "Alice", "age": 10, "grade": "5th"}
print(student.values()) # Prints: dict_values(['Alice', 10, '5th'])
.items() Method
• What it is: Gets all key-value pairs
• What it's used for: Getting complete information
student = {"name": "Alice", "age": 10, "grade": "5th"}
print(student.items()) # Prints: dict_items([('name', 'Alice'), ('age', 10), ('grade',
.get() Method
• What it is: Safely gets a value (won't crash if key doesn't exist)
• What it's used for: Getting values with a backup plan
student = {"name": "Alice", "age": 10}
print(student.get("name")) # Prints: Alice
print(student.get("height")) # Prints: None
print(student.get("height", 0)) # Prints: 0 (default value)
Checking if Keys Exist
in Operator
• What it is: Checks if a key exists in the dictionary
• What it's used for: Avoiding errors when accessing keys
student = {"name": "Alice", "age": 10, "grade": "5th"}
print("name" in student) # Prints: True
print("height" in student) # Prints: False
Nested Dictionaries
• What it is: Dictionaries inside dictionaries
• What it's used for: Storing complex, organized data
school = {
"name": "Pine Elementary",
"students": {
"5th_grade": ["Alice", "Bob", "Charlie"],
"4th_grade": ["David", "Eve", "Frank"]
},
"teachers": {
"math": "Ms. Johnson",
"science": "Mr. Smith"
}
}
print(school["students"]["5th_grade"]) # Prints: ['Alice', 'Bob', 'Charlie']
print(school["teachers"]["math"]) # Prints: Ms. Johnson
Exercise 9: Create a program that stores information about 3 different books (title,
author, year, pages) in a dictionary, then allows the user to: 1. Look up a book by title
2. Add a new book 3. Display all books
11. If Statements - Making Decisions
What are If Statements?
If statements let your program make decisions. They're like asking "If this is true,
then do this."
Basic If Statement
• What it is: Executes code only if a condition is True
• What it's used for: Making decisions in your program
• Syntax:
if condition:
# code to run if condition is True
Example:
age = 10
if age >= 10:
print("You can ride the roller coaster!")
If-Else Statement
• What it is: Does one thing if True, another if False
• What it's used for: Handling both possibilities
• Syntax:
if condition:
# code if True
else:
# code if False
Example:
age = 8
if age >= 10:
print("You can ride the roller coaster!")
else:
print("You're too young for the roller coaster.")
If-Elif-Else Statement
• What it is: Checks multiple conditions in order
• What it's used for: Handling multiple possibilities
• Syntax:
if condition1:
# code if condition1 is True
elif condition2:
# code if condition2 is True
else:
# code if all conditions are False
Example:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
Nested If Statements
• What it is: If statements inside other if statements
• What it's used for: Complex decision making
weather = "sunny"
temperature = 75
if weather == "sunny":
if temperature > 70:
print("Perfect day for the beach!")
else:
print("Sunny but a bit cool.")
else:
print("Maybe stay inside today.")
Combining Conditions
age = 16
has_license = True
if age >= 16 and has_license:
print("You can drive!")
elif age >= 16 and not has_license:
print("You can get a license!")
else:
print("You're too young to drive.")
Exercise 10: Create a simple adventure game where the user makes choices and the
program responds with different outcomes based on their decisions.
12. For Loops - Repeating Actions
What are For Loops?
For loops repeat actions a specific number of times or for each item in a collection.
They're like saying "For each item in this list, do something."
Basic For Loop with Lists
• What it is: Repeats code for each item in a list
• What it's used for: Processing every item in a collection
• Syntax:
for item in list:
# code to repeat
Example:
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(f"I like {fruit}s!")
# Output:
# I like apples!
# I like bananas!
# I like oranges!
For Loop with Strings
word = "Python"
for letter in word:
print(letter)
# Output:
# P
# y
# t
# h
# o
# n
The range() Function
• What it is: Creates a sequence of numbers
• What it's used for: Repeating code a specific number of times
• Syntax: range(start, stop, step)
range(stop)
for i in range(5):
print(i)
# Output: 0, 1, 2, 3, 4
range(start, stop)
for i in range(2, 7):
print(i)
# Output: 2, 3, 4, 5, 6
range(start, stop, step)
for i in range(0, 10, 2):
print(i)
# Output: 0, 2, 4, 6, 8
For Loop with Dictionaries
student = {"name": "Alice", "age": 10, "grade": "5th"}
# Loop through keys
for key in student:
print(key)
# Loop through values
for value in student.values():
print(value)
# Loop through key-value pairs
for key, value in student.items():
print(f"{key}: {value}")
Nested For Loops
• What it is: For loops inside other for loops
• What it's used for: Working with complex data structures
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} × {j} = {i * j}")
print() # Empty line between tables
enumerate() Function
• What it is: Gives you both the index and the item
• What it's used for: When you need to know the position
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Output:
# 0: apple
# 1: banana
# 2: orange
zip() Function
• What it is: Combines multiple lists
• What it's used for: Processing multiple lists together
names = ["Alice", "Bob", "Charlie"]
ages = [10, 11, 12]
grades = ["5th", "5th", "6th"]
for name, age, grade in zip(names, ages, grades):
print(f"{name} is {age} years old and in {grade} grade")
Exercise 11: Create a program that: 1. Asks the user for 5 numbers 2. Stores them in
a list 3. Uses a for loop to find and print the largest number 4. Uses another for loop
to print all even numbers from the list
13. While Loops - Repeating Until Done
What are While Loops?
While loops repeat actions as long as a condition is True. They're like saying "While
this is true, keep doing this."
Basic While Loop
• What it is: Repeats code while a condition is True
• What it's used for: When you don't know how many times to repeat
• Syntax:
while condition:
# code to repeat
Example:
count = 1
while count <= 5:
print(f"Count: {count}")
count = count + 1 # Important: update the condition!
# Output:
# Count: 1
# Count: 2
# Count: 3
# Count: 4
# Count: 5
While Loop with User Input
password = ""
while password != "secret":
password = input("Enter the password: ")
if password != "secret":
print("Wrong password! Try again.")
print("Access granted!")
Infinite Loops (Be Careful!)
# This loop never stops - DON'T RUN THIS!
while True:
print("This will run forever!")
Safe Infinite Loop with Break
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == "quit":
break
print(f"You entered: {user_input}")
While Loop vs For Loop
• For loops: Use when you know how many times to repeat
• While loops: Use when you repeat until a condition changes
# For loop - we know we want 5 numbers
for i in range(5):
print(i)
# While loop - we don't know how many guesses it will take
import random
secret_number = random.randint(1, 10)
guess = 0
while guess != secret_number:
guess = int(input("Guess the number (1-10): "))
Exercise 12: Create a number guessing game where: 1. The computer picks a
random number between 1 and 20 2. The user keeps guessing until they get it right
3. After each wrong guess, tell them if their guess was too high or too low 4. Count
and display how many guesses it took
14. Break and Continue
What are Break and Continue?
Break and continue are special keywords that control how loops work. They let you
exit loops early or skip parts of loops.
Break Statement
• What it is: Exits the loop immediately
• What it's used for: Stopping a loop when a condition is met
• Syntax: break
Example with For Loop:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers:
if number == 5:
break # Stop the loop when we reach 5
print(number)
# Output: 1, 2, 3, 4
Example with While Loop:
count = 0
while True:
count += 1
if count > 3:
break # Exit the infinite loop
print(f"Count: {count}")
# Output:
# Count: 1
# Count: 2
# Count: 3
Continue Statement
• What it is: Skips the rest of the current iteration
• What it's used for: Skipping certain items in a loop
• Syntax: continue
Example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers:
if number % 2 == 0: # If number is even
continue # Skip the rest and go to next number
print(number) # Only prints odd numbers
# Output: 1, 3, 5, 7, 9
Break and Continue with Nested Loops
# Break only exits the innermost loop
for i in range(3):
print(f"Outer loop: {i}")
for j in range(3):
if j == 1:
break # Only exits the inner loop
print(f" Inner loop: {j}")
print("Back in outer loop")
# Output:
# Outer loop: 0
# Inner loop: 0
# Back in outer loop
# Outer loop: 1
# Inner loop: 0
# Back in outer loop
# Outer loop: 2
# Inner loop: 0
# Back in outer loop
Practical Example: Menu System
while True:
print("\n=== MENU ===")
print("1. Say Hello")
print("2. Add Numbers")
print("3. Quit")
choice = input("Enter your choice (1-3): ")
if choice == "1":
name = input("What's your name? ")
print(f"Hello, {name}!")
elif choice == "2":
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(f"Result: {num1 + num2}")
elif choice == "3":
print("Goodbye!")
break # Exit the menu loop
else:
print("Invalid choice! Please try again.")
continue # Go back to the beginning of the loop
Exercise 13: Create a program that: 1. Asks the user to enter numbers 2. Skips
negative numbers (using continue) 3. Stops when the user enters 0 (using break) 4.
Prints the sum of all positive numbers entered
15. Functions - Reusable Code Blocks
What are Functions?
Functions are like recipes or instructions that you can use over and over. Instead of
writing the same code multiple times, you create a function once and call it
whenever you need it.
Creating Functions
• What it is: A named block of code that can be reused
• What it's used for: Organizing code, avoiding repetition
• Syntax:
def function_name():
# code to execute
Simple Function Example:
def say_hello():
print("Hello!")
print("How are you?")
# Call the function
say_hello()
say_hello() # We can call it multiple times
Functions with Parameters
• What it is: Functions that accept input values
• What it's used for: Making functions more flexible
• Syntax:
def function_name(parameter1, parameter2):
# code using parameters
Example:
def greet_person(name):
print(f"Hello, {name}!")
print("Nice to meet you!")
# Call with different names
greet_person("Alice")
greet_person("Bob")
Functions with Multiple Parameters:
def add_numbers(num1, num2):
result = num1 + num2
print(f"{num1} + {num2} = {result}")
add_numbers(5, 3) # Output: 5 + 3 = 8
add_numbers(10, 7) # Output: 10 + 7 = 17
Return Statement
• What it is: Sends a value back from the function
• What it's used for: Getting results from functions
• Syntax: return value
Example:
def multiply_numbers(num1, num2):
result = num1 * num2
return result
# Store the result
answer = multiply_numbers(4, 5)
print(f"The answer is {answer}") # Output: The answer is 20
Function with Return Value:
def calculate_area(length, width):
area = length * width
return area
# Use the returned value
room_area = calculate_area(12, 10)
print(f"Room area: {room_area} square feet")
Default Parameters
• What it is: Parameters with default values
• What it's used for: Making some parameters optional
def greet_person(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet_person("Alice") # Output: Hello, Alice!
greet_person("Bob", "Hi") # Output: Hi, Bob!
greet_person("Charlie", "Hey") # Output: Hey, Charlie!
Functions Returning Multiple Values
def get_name_and_age():
name = input("What's your name? ")
age = int(input("How old are you? "))
return name, age
# Get both values
person_name, person_age = get_name_and_age()
print(f"{person_name} is {person_age} years old")
Local vs Global Variables
• Local variables: Only exist inside the function
• Global variables: Exist throughout the program
# Global variable
total_score = 0
def add_points(points):
# Local variable
bonus = 10
global total_score
total_score += points + bonus
print(f"Added {points + bonus} points")
add_points(50)
print(f"Total score: {total_score}") # Output: Total score: 60
Docstrings
• What it is: Documentation for functions
• What it's used for: Explaining what functions do
def calculate_circle_area(radius):
"""
Calculate the area of a circle.
Args:
radius: The radius of the circle
Returns:
The area of the circle
"""
pi = 3.14159
area = pi * radius * radius
return area
# You can access the docstring
print(calculate_circle_area.__doc__)
Function Examples:
# Function to check if a number is even
def is_even(number):
return number % 2 == 0
# Function to find the largest number in a list
def find_largest(numbers):
if not numbers: # Empty list
return None
largest = numbers[0]
for num in numbers:
if num > largest:
largest = num
return largest
# Function to create a simple calculator
def calculator(num1, num2, operation):
if operation == "+":
return num1 + num2
elif operation == "-":
return num1 - num2
elif operation == "*":
return num1 * num2
elif operation == "/":
if num2 != 0:
return num1 / num2
else:
return "Error: Division by zero"
else:
return "Error: Invalid operation"
# Using the functions
print(is_even(4)) # True
print(find_largest([3, 7, 2, 9, 1])) # 9
print(calculator(10, 5, "+")) # 15
Exercise 14: Create the following functions: 1. A function that converts temperature
from Celsius to Fahrenheit 2. A function that checks if a word is a palindrome (reads
the same forwards and backwards) 3. A function that takes a list of numbers and
returns the average 4. A function that generates a simple password based on a name
and a number
16. Modules and Packages
What are Modules?
Modules are files containing Python code that you can use in other programs.
They're like toolboxes - you can import them to use their functions, variables, and
classes.
Importing Modules
• What it is: Bringing code from other files into your program
• What it's used for: Using pre-written code, organizing your code
• Syntax: import module_name
Using Built-in Modules
math Module
• What it is: Mathematical functions and constants
• What it's used for: Advanced math operations
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
print(math.ceil(4.2)) # 5 (round up)
print(math.floor(4.8)) # 4 (round down)
print(math.pow(2, 3)) # 8.0 (2 to the power of 3)
random Module
• What it is: Functions for generating random numbers
• What it's used for: Games, simulations, random choices
import random
print(random.randint(1, 6)) # Random number between 1 and 6
print(random.choice(['red', 'blue', 'green'])) # Random choice from list
print(random.random()) # Random float between 0 and 1
# Shuffle a list
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers) # Numbers in random order
datetime Module
• What it is: Working with dates and times
• What it's used for: Getting current time, calculating dates
import datetime
# Current date and time
now = datetime.datetime.now()
print(now)
# Current date only
today = datetime.date.today()
print(today)
# Format dates
print(now.strftime("%Y-%m-%d")) # 2024-01-15
print(now.strftime("%B %d, %Y")) # January 15, 2024
Different Ways to Import
Import Specific Functions
from math import sqrt, pi
print(sqrt(16)) # No need to write math.sqrt
print(pi)
Import with Alias
import datetime as dt
now = dt.datetime.now()
print(now)
Import All (Not Recommended)
from math import *
print(sqrt(16)) # Can use all math functions directly
Creating Your Own Modules
Step 1: Create a file called my_functions.py
# my_functions.py
def greet(name):
return f"Hello, {name}!"
def add_numbers(a, b):
return a + b
PI = 3.14159
def circle_area(radius):
return PI * radius * radius
Step 2: Use your module in another file
# main.py
import my_functions
print(my_functions.greet("Alice"))
print(my_functions.add_numbers(5, 3))
print(my_functions.circle_area(5))
Useful Built-in Modules
os Module
• What it is: Operating system interface
• What it's used for: File system operations
import os
print(os.getcwd()) # Current directory
print(os.listdir('.')) # List files in current directory
sys Module
• What it is: System-specific parameters and functions
• What it's used for: System information, command line arguments
import sys
print(sys.version) # Python version
print(sys.platform) # Operating system
json Module
• What it is: Working with JSON data
• What it's used for: Saving and loading data
import json
# Convert Python data to JSON
data = {"name": "Alice", "age": 10}
json_string = json.dumps(data)
print(json_string) # {"name": "Alice", "age": 10}
# Convert JSON to Python data
python_data = json.loads(json_string)
print(python_data) # {'name': 'Alice', 'age': 10}
The if __name__ == "__main__": Pattern
• What it is: Code that only runs when the file is executed directly
• What it's used for: Testing modules
# my_module.py
def my_function():
print("This is my function")
# This only runs when the file is executed directly
if __name__ == "__main__":
print("This module is being run directly")
my_function()
Exercise 15: Create a module called game_utils.py with functions for: 1. Rolling a
dice (random number 1-6) 2. Flipping a coin (heads or tails) 3. Generating a random
color from a list 4. Creating a simple guessing game function Then import and use
these functions in a main program.
17. File Handling - Reading and Writing Files
What is File Handling?
File handling lets your program read information from files and save information to
files. It's like your program can read books and write diaries!
Reading Files
Basic File Reading
• What it is: Opening and reading the contents of a file
• What it's used for: Loading data, reading configurations
• Syntax: open(filename, mode)
# Reading a text file
file = open("story.txt", "r") # "r" means read mode
content = file.read() # Read entire file
print(content)
file.close() # Always close the file!
Better Way: Using with Statement
• What it is: Automatically closes the file when done
• What it's used for: Safer file handling
with open("story.txt", "r") as file:
content = file.read()
print(content)
# File is automatically closed here
Reading Line by Line
with open("story.txt", "r") as file:
for line in file:
print(line.strip()) # strip() removes extra newlines
Reading All Lines into a List
with open("story.txt", "r") as file:
lines = file.readlines()
for i, line in enumerate(lines):
print(f"Line {i+1}: {line.strip()}")
Writing Files
Basic File Writing
• What it is: Creating or overwriting a file with new content
• What it's used for: Saving data, creating reports
with open("output.txt", "w") as file: # "w" means write mode
file.write("Hello, World!\n")
file.write("This is a new file.\n")
Appending to Files
• What it is: Adding content to the end of an existing file
• What it's used for: Adding to logs, keeping records
with open("diary.txt", "a") as file: # "a" means append mode
file.write("Today I learned about file handling!\n")
File Modes
• "r": Read mode (default) - opens existing file for reading
• "w": Write mode - creates new file or overwrites existing
• "a": Append mode - adds to end of existing file
• "r+": Read and write mode
• "x": Create mode - creates new file, fails if file exists
Working with CSV Files
Writing CSV Files
import csv
students = [
["Name", "Age", "Grade"],
["Alice", 10, "5th"],
["Bob", 11, "5th"],
["Charlie", 12, "6th"]
]
with open("students.csv", "w", newline="") as file:
writer = csv.writer(file)
for row in students:
writer.writerow(row)
Reading CSV Files
import csv
with open("students.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Error Handling with Files
try:
with open("nonexistent.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("File not found! Please check the filename.")
except PermissionError:
print("Permission denied! You don't have access to this file.")
Practical File Examples
Simple Todo List
def save_todo_list(tasks):
with open("todo.txt", "w") as file:
for task in tasks:
file.write(task + "\n")
def load_todo_list():
try:
with open("todo.txt", "r") as file:
tasks = []
for line in file:
tasks.append(line.strip())
return tasks
except FileNotFoundError:
return [] # Return empty list if file doesn't exist
# Usage
todo_list = load_todo_list()
todo_list.append("Learn Python")
todo_list.append("Practice coding")
save_todo_list(todo_list)
Simple Log File
import datetime
def log_message(message):
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open("program.log", "a") as file:
file.write(f"[{timestamp}] {message}\n")
# Usage
log_message("Program started")
log_message("User logged in")
log_message("Program ended")
File Path Handling
import os
# Get current directory
current_dir = os.getcwd()
print(f"Current directory: {current_dir}")
# Join paths safely
file_path = os.path.join("data", "students.txt")
print(f"File path: {file_path}")
# Check if file exists
if os.path.exists(file_path):
print("File exists!")
else:
print("File does not exist.")
Exercise 16: Create a simple grade book program that: 1. Saves student names and
grades to a file 2. Loads the data when the program starts 3. Allows adding new
students and grades 4. Calculates and displays the class average 5. Saves everything
when the program exits
18. Error Handling - Dealing with Mistakes
What is Error Handling?
Error handling is like having a safety net for your program. When something goes
wrong, instead of crashing, your program can handle the error gracefully and keep
running.
Types of Errors
Syntax Errors
• What it is: Mistakes in how you write Python code
• What it's used for: Python can't understand your code
# This will cause a syntax error
print("Hello World" # Missing closing parenthesis
Runtime Errors (Exceptions)
• What it is: Errors that happen while your program is running
• What it's used for: Handling unexpected situations
# This will cause a runtime error
number = int("hello") # Can't convert "hello" to integer
Try-Except Blocks
• What it is: Code that tries something and handles errors
• What it's used for: Preventing crashes, handling user mistakes
• Syntax:
try:
# code that might cause an error
pass
except ErrorType:
# code to handle the error
pass
Basic Exception Handling
try:
age = int(input("Enter your age: "))
print(f"You are {age} years old")
except ValueError:
print("That's not a valid number!")
Handling Multiple Exceptions
try:
numbers = [1, 2, 3]
index = int(input("Enter an index: "))
print(numbers[index])
except ValueError:
print("Please enter a valid number!")
except IndexError:
print("That index is out of range!")
Catching Any Exception
try:
# Some risky code
result = 10 / 0
except Exception as e:
print(f"An error occurred: {e}")
Try-Except-Else-Finally
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
except PermissionError:
print("Permission denied!")
else:
print("File read successfully!")
print(content)
finally:
try:
file.close()
print("File closed")
except:
print("No file to close")
Common Exception Types
ValueError
• What it is: Invalid value for the operation
• When it happens: Converting invalid strings to numbers
try:
number = int("abc")
except ValueError:
print("Cannot convert 'abc' to a number")
ZeroDivisionError
• What it is: Dividing by zero
• When it happens: Mathematical division by zero
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
IndexError
• What it is: List index out of range
• When it happens: Accessing non-existent list positions ``` try: numbers = [1,
2, 3] print(numbers[10]) except IndexError: print("Index out of range
KeyError
• What it is: Key doesn't exist in dictionary
• When it happens: Accessing non-existent dictionary keys
try:
student = {"name": "Alice", "age": 10}
print(student["grade"])
except KeyError:
print("That key doesn't exist in the dictionary!")
FileNotFoundError
• What it is: File doesn't exist
• When it happens: Trying to open non-existent files
try:
with open("missing_file.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found! Please check the filename.")
Practical Error Handling Examples
Safe Calculator
def safe_calculator():
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operation = input("Enter operation (+, -, *, /): ")
if operation == "+":
result = num1 + num2
elif operation == "-":
result = num1 - num2
elif operation == "*":
result = num1 * num2
elif operation == "/":
result = num1 / num2
else:
print("Invalid operation!")
return
print(f"Result: {result}")
except ValueError:
print("Please enter valid numbers!")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Usage
safe_calculator()
Safe File Reader
def safe_file_reader(filename):
try:
with open(filename, "r") as file:
content = file.read()
print("File contents:")
print(content)
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
except PermissionError:
print(f"Error: Permission denied to read '{filename}'.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Usage
safe_file_reader("data.txt")
Raising Custom Exceptions
• What it is: Creating your own error messages
• What it's used for: Validating data, enforcing rules
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
if age > 150:
raise ValueError("Age seems unrealistic!")
return True
try:
user_age = int(input("Enter your age: "))
check_age(user_age)
print(f"Age {user_age} is valid!")
except ValueError as e:
print(f"Invalid age: {e}")
Exercise 17:
Create a program that: 1. Asks the user to enter student grades (0-100) 2. Handles
invalid input (non-numbers, negative numbers, numbers > 100) 3. Calculates the
average when the user enters "done" 4. Saves the grades to a file, handling file errors
5. Displays appropriate error messages for each type of error
19. Tuples and Sets
What are Tuples?
Tuples are like lists, but they can't be changed after creation. They're perfect for
storing data that shouldn't be modified.
Creating Tuples
• What it is: An ordered collection of items that cannot be changed
• What it's used for: Storing fixed data, coordinates, database records
• Syntax: (item1, item2, item3)
# Empty tuple
empty_tuple = ()
# Tuple with values
coordinates = (10, 20)
colors = ("red", "green", "blue")
mixed_tuple = (1, "hello", 3.14, True)
# Single item tuple (note the comma!)
single_item = (42,) # Without comma, it's just parentheses
print(coordinates) # (10, 20)
print(len(colors)) # 3
Accessing Tuple Items
coordinates = (10, 20, 30)
print(coordinates[0]) # 10
print(coordinates[-1]) # 30 (last item)
print(coordinates[1:3]) # (20, 30)
Tuple Methods
numbers = (1, 2, 3, 2, 4, 2)
# Count occurrences
print(numbers.count(2)) # 3
# Find index of first occurrence
print(numbers.index(3)) # 2
Tuple Unpacking
• What it is: Assigning tuple items to variables
• What it's used for: Getting multiple values at once
point = (10, 20)
x, y = point
print(f"X: {x}, Y: {y}") # X: 10, Y: 20
# Swapping variables
a = 5
b = 10
a, b = b, a
print(f"a: {a}, b: {b}") # a: 10, b: 5
What are Sets?
Sets are collections of unique items. They automatically remove duplicates and are
great for finding common elements.
Creating Sets
• What it is: A collection of unique items with no order
• What it's used for: Removing duplicates, finding common elements
• Syntax: {item1, item2, item3} or set()
# Empty set
empty_set = set() # Note: {} creates an empty dictionary
# Set with values
fruits = {"apple", "banana", "orange"}
numbers = {1, 2, 3, 4, 5}
# Set from list (removes duplicates)
numbers_list = [1, 2, 2, 3, 3, 4, 5]
unique_numbers = set(numbers_list)
print(unique_numbers) # {1, 2, 3, 4, 5}
Set Operations
fruits = {"apple", "banana", "orange"}
# Add item
fruits.add("grape")
print(fruits) # {'apple', 'banana', 'orange', 'grape'}
# Remove item
fruits.remove("banana") # Raises error if item doesn't exist
fruits.discard("banana") # Doesn't raise error if item doesn't exist
# Check if item exists
print("apple" in fruits) # True
# Clear all items
fruits.clear()
Set Mathematical Operations
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Union (all items from both sets)
union = set1 | set2
print(union) # {1, 2, 3, 4, 5, 6, 7, 8}
# Intersection (common items)
intersection = set1 & set2
print(intersection) # {4, 5}
# Difference (items in set1 but not in set2)
difference = set1 - set2
print(difference) # {1, 2, 3}
# Symmetric difference (items in either set, but not both)
sym_diff = set1 ^ set2
print(sym_diff) # {1, 2, 3, 6, 7, 8}
Practical Examples
Removing Duplicates
def remove_duplicates(items):
return list(set(items))
# Usage
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = remove_duplicates(numbers)
print(unique_numbers) # [1, 2, 3, 4, 5]
Finding Common Elements
def find_common_interests(person1_interests, person2_interests):
set1 = set(person1_interests)
set2 = set(person2_interests)
return list(set1 & set2)
# Usage
alice_interests = ["reading", "swimming", "coding", "music"]
bob_interests = ["music", "gaming", "reading", "sports"]
common = find_common_interests(alice_interests, bob_interests)
print(f"Common interests: {common}") # ['music', 'reading']
Exercise 18:
Create a program that: 1. Stores student information as tuples (name, age, grade) in
a list 2. Creates sets of students by grade level 3. Finds students who are in multiple
activities (using set operations) 4. Removes duplicate student entries 5. Displays the
results in a formatted way
20. List Comprehensions
What are List Comprehensions?
List comprehensions are a concise way to create lists. They're like a shortcut for
writing loops that create lists.
Basic List Comprehension
• What it is: A compact way to create lists using a single line
• What it's used for: Transforming data, filtering lists
• Syntax: [expression for item in iterable]
# Traditional way
squares = []
for x in range(5):
squares.append(x ** 2)
print(squares) # [0, 1, 4, 9, 16]
# List comprehension way
squares = [x ** 2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
List Comprehension with Conditions
• Syntax: [expression for item in iterable if condition]
# Get even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = [x for x in numbers if x % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
# Get squares of even numbers
even_squares = [x ** 2 for x in numbers if x % 2 == 0]
print(even_squares) # [4, 16, 36, 64, 100]
Working with Strings
# Convert to uppercase
words = ["hello", "world", "python"]
uppercase_words = [word.upper() for word in words]
print(uppercase_words) # ['HELLO', 'WORLD', 'PYTHON']
# Get lengths of words
word_lengths = [len(word) for word in words]
print(word_lengths) # [5, 5, 6]
# Get words longer than 5 characters
long_words = [word for word in words if len(word) > 5]
print(long_words) # ['python']
Nested List Comprehensions
# Create a multiplication table
multiplication_table = [[i * j for j in range(1, 6)] for i in range(1, 6)]
print(multiplication_table)
# [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [5, 10, 15,
# Flatten a nested list
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [item for sublist in nested_list for item in sublist]
print(flattened) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
Practical Examples
Grade Processing
# Student grades
grades = [85, 92, 78, 96, 88, 76, 94, 89]
# Get letter grades
def get_letter_grade(score):
if score >= 90: return 'A'
elif score >= 80: return 'B'
elif score >= 70: return 'C'
elif score >= 60: return 'D'
else: return 'F'
letter_grades = [get_letter_grade(grade) for grade in grades]
print(letter_grades) # ['B', 'A', 'C', 'A', 'B', 'C', 'A', 'B']
# Get only passing grades (>= 70)
passing_grades = [grade for grade in grades if grade >= 70]
print(passing_grades) # [85, 92, 78, 96, 88, 76, 94, 89]
Text Processing
sentence = "The quick brown fox jumps over the lazy dog"
words = sentence.split()
# Get words starting with vowels
vowels = 'aeiouAEIOU'
vowel_words = [word for word in words if word[0] in vowels]
print(vowel_words) # ['over']
# Get words with more than 4 letters
long_words = [word for word in words if len(word) > 4]
print(long_words) # ['quick', 'brown', 'jumps']
Exercise 19:
Create a program that: 1. Takes a list of numbers from user input 2. Uses list
comprehensions to create: - A list of squares of even numbers - A list of numbers
divisible by 3 - A list of absolute values (if any negative numbers) 3. Processes a list
of student names to: - Create initials for each name - Find names that start with a
specific letter - Convert all names to title case
21. Dictionary and Set Comprehensions
Dictionary Comprehensions
Dictionary comprehensions create dictionaries in a concise way, similar to list
comprehensions.
Basic Dictionary Comprehension
• What it is: A compact way to create dictionaries
• What it's used for: Transforming data into key-value pairs
• Syntax: {key_expression: value_expression for item in iterable}
# Traditional way
squares_dict = {}
for x in range(5):
squares_dict[x] = x ** 2
print(squares_dict) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Dictionary comprehension way
squares_dict = {x: x ** 2 for x in range(5)}
print(squares_dict) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Dictionary Comprehension with Conditions
# Create dictionary of even numbers and their squares
even_squares = {x: x ** 2 for x in range(10) if x % 2 == 0}
print(even_squares) # {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
# Grade categories
grades = {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'Diana': 96}
high_grades = {name: grade for name, grade in grades.items() if grade >= 90}
print(high_grades) # {'Bob': 92, 'Diana': 96}
Working with Existing Data
# Flip dictionary (swap keys and values)
original = {'a': 1, 'b': 2, 'c': 3}
flipped = {value: key for key, value in original.items()}
print(flipped) # {1: 'a', 2: 'b', 3: 'c'}
# Create word lengths dictionary
words = ['apple', 'banana', 'cherry']
word_lengths = {word: len(word) for word in words}
print(word_lengths) # {'apple': 5, 'banana': 6, 'cherry': 6}
Set Comprehensions
Set comprehensions create sets in a concise way.
Basic Set Comprehension
• What it is: A compact way to create sets
• What it's used for: Creating unique collections
• Syntax: {expression for item in iterable}
# Traditional way
unique_squares = set()
for x in range(10):
unique_squares.add(x ** 2)
print(unique_squares) # {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}
# Set comprehension way
unique_squares = {x ** 2 for x in range(10)}
print(unique_squares) # {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}
Set Comprehension with Conditions
# Get unique vowels from a sentence
sentence = "The quick brown fox jumps over the lazy dog"
vowels = {char.lower() for char in sentence if char.lower() in 'aeiou'}
print(vowels) # {'e', 'u', 'i', 'o', 'a'}
# Get unique word lengths
words = ['apple', 'banana', 'cherry', 'date', 'elderberry']
unique_lengths = {len(word) for word in words}
print(unique_lengths) # {4, 5, 6, 10}
Practical Examples
Student Grade Analysis
students = [
{'name': 'Alice', 'grade': 85, 'subject': 'Math'},
{'name': 'Bob', 'grade': 92, 'subject': 'Science'},
{'name': 'Charlie', 'grade': 78, 'subject': 'Math'},
{'name': 'Diana', 'grade': 96, 'subject': 'Science'},
{'name': 'Eve', 'grade': 88, 'subject': 'English'}
]
# Create dictionary of student names and grades
name_grades = {student['name']: student['grade'] for student in students}
print(name_grades) # {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'Diana': 96, 'Eve': 88}
# Get high achievers (grade >= 90)
high_achievers = {student['name']: student['grade'] for student in students if student['
print(high_achievers) # {'Bob': 92, 'Diana': 96}
# Get unique subjects
unique_subjects = {student['subject'] for student in students}
print(unique_subjects) # {'Math', 'Science', 'English'}
Text Analysis
text = "The quick brown fox jumps over the lazy dog"
words = text.lower().split()
# Count word frequencies
word_count = {word: words.count(word) for word in set(words)}
print(word_count) # {'the': 2, 'quick': 1, 'brown': 1, ...}
# Get words starting with each letter
first_letters = {word[0]: word for word in words}
print(first_letters) # {'t': 'the', 'q': 'quick', 'b': 'brown', ...}
# Get unique first letters
unique_first_letters = {word[0] for word in words}
print(unique_first_letters) # {'t', 'q', 'b', 'f', 'j', 'o', 'l', 'd'}
Exercise 20:
Create a program that: 1. Takes a list of employee data (name, department, salary) 2.
Uses dictionary comprehensions to create: - A dictionary of employee names and
salaries - A dictionary of high-paid employees (salary > 50000) - A dictionary of
employees by department 3. Uses set comprehensions to find: - Unique departments
- Unique salary ranges (in thousands) - Employees whose names start with the same
letter
This continuation maintains the same educational approach, clear explanations, and
practical examples as the original document. Each concept builds upon previous
knowledge while introducing new programming techniques that students can
immediately apply.
Advanced python
Chapter 22: Object-Oriented Programming
" Imagine you want to build lots of toy cars. You wouldn't draw each
car from scratch every time, right? You'd have a blueprint or a
design for a car, and then you'd use that blueprint to make many
cars.
What is OOP?
OOP (say "Oh-Oh-Pee") is like having super blueprints for your code! Instead of just
writing steps for the computer to follow, we create our own special "types" of things.
It helps us keep our code neat and tidy, like putting all your toys in their right boxes!
Classes and Objects
What it is:
• A Class is like that blueprint for your toy car. It's the design or idea of what
something should be like.
• An Object is the actual toy car you built from the blueprint. You can have
many toy cars from the same blueprint!
Why use it?
• To group stuff together: Imagine your toy car has wheels, doors, and can
drive. We can put all these "parts" and "actions" (like driving) together in our
blueprint!
• To model real-world things: We can make blueprints for dogs, cats, books, or
anything you can think of in the real world and then make them in our code!
Creating a Class
Let's make a blueprint for a Dog!
class Dog: # This is our blueprint for a Dog!
def bark(self): # This is an action our Dog can do: bark!
print("Woof!")
# Now, let's make a real dog from our blueprint!
my_dog = Dog()
my_dog.bark() # What do you think this will say? "Woof!"
See? We made a dog object, and it can bark just like we told it in our blueprint!
The __init__ Method
Imagine when you build a toy car, you want to give it a color and a name right away.
The __init__ (say "under-under-init-under-under") method is like the special step in
your blueprint that helps you set up your new object as soon as you make it!
class Dog:
def __init__(self, name, age): # When we make a Dog, we give it a name and age!
self.name = name # We remember the dog's name
self.age = age # We remember the dog's age
def bark(self):
print(f"{self.name} says Woof!") # Now the bark knows the dog's name!
# Let's make a dog named "Buddy" who is 3 years old!
my_dog = Dog("Buddy", 3)
my_dog.bark() # Buddy says Woof!
Now our dogs have names and ages! How cool is that?
Inheritance
Sometimes, you have a blueprint for a general animal, and then you want to make a
dog blueprint that is like an animal blueprint, but with some special doggy things.
That's inheritance! It's like building on top of an existing blueprint.
class Animal: # This is a general blueprint for any animal
def speak(self):
print("Animal speaks")
class Dog(Animal): # Our Dog blueprint is based on the Animal blueprint!
def speak(self): # Dogs speak differently, so we change it for them!
print("Dog barks")
dog = Dog()
dog.speak() # Dog barks (because our Dog blueprint told it to bark!)
Our dog can do what an animal does, but it also has its own special way of speaking!
Special Methods (Magic Methods)
These are like secret powers for your objects! They have double underscores (like __)
at the start and end. They help your objects do cool things automatically.
• __str__ (say "under-under-string-under-under") – This is like telling Python,
"Hey, when you want to show my object as text, make it look like this!"
• __len__ (say "under-under-length-under-under") – If your object has a length
(like a list or a book with pages), this tells Python how to figure it out.
class Book:
def __init__(self, title):
self.title = title
def __str__(self): # This tells Python how to show a Book as text!
return f"Book: {self.title}"
book = Book("Python 101")
print(book) # Book: Python 101
Now, when you print our book object, it looks nice and friendly!
Exercise 20: Ready for a challenge?
Create a class called Car that has a make (like Toyota), a model (like Camry), and a
year (like 2023).
Add a special action (a method) called drive that prints "Vroom!"
Make a real Car object from your blueprint and make it drive!
Chapter 23: Advanced Python Features
Now, let's learn some even more super powers of Python!
Iterators and Generators
Imagine you have a big list of numbers, and you want to look at them one by one,
without keeping all of them in your head at once.
Iterators
These are like special pointers that help you go through things one by one. You ask
for the next one, and it gives it to you!
my_list = [1, 2, 3]
iterator = iter(my_list) # Ask Python to give us an iterator for our list
print(next(iterator)) # 1 (Give me the next number!)
print(next(iterator)) # 2 (Give me the next number!)
Generators
These are like special "function factories" that create iterators. They are super smart
because they don't make all the numbers at once; they make them one by one only
when you ask for them, which saves computer memory!
def count_up_to(n): # This is our generator function
count = 1
while count <= n:
yield count # "yield" is like "give me this one, and remember where I stopped!"
count += 1
# We can use it in a loop!
for number in count_up_to(3):
print(number) # This will print 1, then 2, then 3
Generators are like magic because they can give you a lot of numbers without having
to store them all at once!
Decorators
Imagine you have a friend who always adds a "Hello!" at the start and a "Goodbye!" at
the end of whatever you say. A decorator is like that friend! It's a special way to add
extra actions around another function, without actually changing the original
function.
def decorator(func): # This is our special "friend" function
def wrapper(): # This is what our friend *does*
print("Before function") # Says "Before function"
func() # Then does what you asked
print("After function") # Then says "After function"
return wrapper
@decorator # This is the magic! It's like telling Python, "Use my friend!"
def say_hello():
print("Hello!") # This is what *you* wanted to say
say_hello() # This will now say "Before function", then "Hello!", then "After function"
Decorators are super handy for adding extra powers to your functions!
Context Managers
Imagine you open a book to read, and when you're done, you always close it. A
context manager helps you do things like that automatically! It makes sure that
something is "cleaned up" or closed properly, even if something goes wrong.
with open("file.txt", "w") as f: # "with" is the magic word for context managers!
f.write("Hello!") # We write "Hello!" to a file
# When we're done here, Python automatically closes the file for us! No need to remember
This is super safe because you don't have to worry about forgetting to close a file or
other resources.
⚡ Lambda Functions
What if you need a tiny, quick function that only does one simple thing? Like adding
two numbers? That's where lambda functions come in! They're like super small, one-
line functions.
add = lambda x, y: x + y # This is a lambda function!
print(add(3, 5)) # 8 (It adds 3 and 5!)
They're great for quick jobs where you don't need a whole big def function.
Exercise 21: Another big brain challenge!
Write a generator that gives you the squares of numbers from 1 to 5. (Remember,
square means a number multiplied by itself, like 2 × 2 = 4).
Write a decorator that prints "Start" before a function runs and "End" after it
finishes.
Use a lambda function to multiply two numbers together.
Chapter 24: Standard Library Essentials
Python comes with a huge toolbox of amazing things already built in! These are
called the Standard Library. Let's look at some super useful tools in it!
Important Built-in Functions
These are functions that Python already knows how to do!
• len() – How many items are there? (Like how many toys in your toy box!)
• sum() – Add up all the numbers in a list!
• max() – Find the biggest number!
• min() – Find the smallest number!
• sorted() – Put a list in order, from smallest to biggest!
• zip() – Combine two lists together, like zipping up two zippers!
Working with Dates and Times
Ever wondered how to tell the computer what time it is, or what date it is? Python
has a special tool for that called datetime!
from datetime import datetime # We "import" this tool from Python's toolbox
now = datetime.now() # Ask Python: "What's the date and time right now?"
print(now) # This will show you the current date and time (like 2025-07-07 23:06:53.123
print(now.strftime("%Y-%m-%d")) # This makes the date look nice, like "2025-07-07"
Now you can make your programs know about time!
Regular Expressions
What if you have a big story, and you want to find all the phone numbers, or all the
words that start with "P"? Regular expressions (or regex for short) are like super-
powered search tools for text!
import re # We need to import the "re" tool for regular expressions
pattern = r"\d+" # This is a secret code: "\d+" means "find one or more digits (numbers
result = re.findall(pattern, "There are 24 apples and 7 oranges.") # Find the pattern i
print(result) # ['24', '7'] (It found the numbers!)
Regex can be a bit tricky at first, but they are super powerful for finding things in
text!
JSON and Data Serialization
Imagine you have a bunch of information, like your friend's name and age. You want
to save it to a file so another computer program (or even you later) can read it easily.
JSON (say "Jay-Son") is a special way to save data that both computers and humans
can understand.
• Serialization: Turning Python information (like a dictionary) into a text
format (like JSON) that can be saved or sent.
• Deserialization: Turning that text format (like JSON) back into Python
information!
import json # We import the "json" tool
data = {"name": "Alice", "age": 10} # This is our Python information (a dictionary)
json_str = json.dumps(data) # "dumps" means turn Python data INTO JSON text
print(json_str) # {"name": "Alice", "age": 10} (Looks like text now!)
data_back = json.loads(json_str) # "loads" means turn JSON text BACK INTO Python data
print(data_back) # {'name': 'Alice', 'age': 10} (Back to Python data!)
JSON is super important for sending information between different computer
programs!
Exercise 22: Time for some more practice!
Write code that prints today's date using the datetime tool.
Use the re tool to find all words starting with "P" in the sentence: "Python
programming is powerful and fun."
Convert a Python dictionary (like {"city": "New York", "population": 8000000})
into JSON text and then back into a Python dictionary.
Chapter 25: Final Projects and Quiz
Wow, you've learned so much! Now it's time to put your super Python skills to the
test with some fun projects and a quiz!
Practice Projects
These are like big challenges to help you build real things!
1. Calculator App: Make a program that can add, subtract, multiply, and divide
numbers. It should keep working until the user says "stop!"
2. Todo List: Make a program where you can add tasks, remove tasks, and see all
your tasks. Make it save your tasks to a file so you don't lose them!
3. Quiz Game: Create a game that asks 5 questions. At the end, tell the player their
score!
4. Contact Book: Make a program to save names, phone numbers, and emails. You
should be able to search for a contact!
5. Number Guessing Game: The computer picks a secret number, and the user
tries to guess it. Tell them if their guess is too high or too low!
Final Quiz
Let's test your super brain! Try to answer these questions without looking back!
1. What is the difference between a list and a tuple? (Hint: One can change, the
other cannot!)
2. How do you open a file safely so it always closes automatically? (Hint: Think
about that magic word!)
3. What does @decorator mean? (Hint: It adds extra powers!)
4. Write a function that returns True if a number is even (divisible by 2) and False
if it's odd.
5. What does json.loads() do? (Hint: It "loads" something back!)
6. How do you create a class called Person that has a name attribute? (Hint: Think
about the __init__ method!)
7. Write a list comprehension to get the squares of numbers from 1 to 5. (Hint:
It's a short way to make a list!)
8. What does the with statement do when working with files? (Hint: It manages
something automatically!)
9. What is a generator? (Hint: It "yields" things one by one!)
10. What is OOP and why is it useful? (Hint: Blueprints and organizing code!)
Congratulations, Python Master!
You've completed your amazing Python journey from a tiny little coder to a super
Python master! Remember, the best way to get even better is to keep practicing and
build more awesome projects!
Keep coding and have fun! The world needs your amazing programs!
" "The only way to learn a new programming language is by writing
programs in it." - Dennis Ritchie