🐍 What is Python?
📌 1. Definition
Python is a high-level, interpreted, general-purpose programming language. It was created by Guido van Rossum and released in 1991.
Python is known for its clear syntax and readability, which makes it a popular language for both beginners and experienced developers.
📌 2. History and Background
Python was developed in the late 1980s by Guido van Rossum at the National Research Institute for Mathematics and Computer Science in the Netherlands. The language was named after the British comedy group Monty Python.
📌 3. Key Features of Python
- Simple and Easy to Learn: Python has a simple syntax similar to English
- Interpreted: Python code is executed line by line, making debugging easier
- Cross-platform: Runs on Windows, macOS, Linux, and more
- Large Standard Library: Comes with extensive built-in modules
- Object-Oriented: Supports object-oriented programming concepts
📌 4. What is Python Used For?
- Web Development (Django, Flask)
- Data Science and Analytics
- Machine Learning and AI
- Automation and Scripting
- Desktop Applications
- Scientific Computing
📌 5. Python 2 vs Python 3
✅ Today, always use Python 3.x.
Python 2 reached end-of-life on January 1, 2020, and is no longer supported. Python 3 has many improvements and new features.
📌 6. Advantages of Python
- Simple syntax makes it easy to write and debug
- Rapid development – fewer lines of code compared to other languages
- Large ecosystem of third-party libraries (PyPI)
- Strong support for integration with other languages and tools
- Popular in academia, industry, and research
📌 7. Disadvantages of Python
- Slower than compiled languages like C/C++
- Not ideal for mobile app development
- High memory usage compared to low-level languages
- Limited in multithreading due to the Global Interpreter Lock (GIL)
📌 8. Python Syntax Example
# Simple Python program
name = input("Enter your name: ")
print("Hello, " + name)
This simple program asks for your name and greets you!
Practice Editor
🐍 Getting Started with Python
📌 1. What You Need to Begin
- A computer (Windows, macOS, or Linux)
- Internet connection (for downloading Python or using online editors)
- A text editor or an IDE (like VS Code, PyCharm, or IDLE)
📌 2. Installing Python
✅ Official Website:
Download Python from: 👉 https://www.python.org/downloads/
📦 Steps:
- Choose the version (always go for the latest Python 3.x)
- During installation:
- Check the box "Add Python to PATH"
- Click Install Now
✅ Verify Installation:
Open your terminal (CMD, PowerShell, or Bash):
python --version
or
python3 --version
📌 3. Writing Your First Python Program
You can write Python code in:
- IDLE (comes with Python)
- VS Code, PyCharm, Jupyter Notebook
- Online editors like:
✅ First Program:
print("Hello, World!")
💡 What it does: It tells Python to display the message "Hello, World!" on the screen.
📌 4. Python File Basics
- Python files end with
.py
- To run a script:
python yourfile.py
📌 5. Basic Python Syntax
🔹 Comments
# This is a comment
🔹 Variables
name = "Alice"
age = 25
🔹 Input and Output
name = input("Enter your name: ")
print("Hello,", name)
🐍 Python Syntax: The Basics
📌 1. Python is Indentation-Sensitive
Python uses indentation (spaces or tabs) to define blocks of code. This is different from many other languages that use curly braces {}.
# Correct
if 5 > 3:
print("Yes")
# Incorrect (no indentation)
if 5 > 3:
print("Yes") # ❌ Error
📌 2. Comments
Used to explain code. They are ignored by Python.
# This is a single-line comment
"""
This is a
multi-line comment
"""
📌 3. Print Statement
Used to display output.
print("Hello, World!")
📌 4. Variables and Data Types
No need to declare data types; Python is dynamically typed.
x = 10 # Integer
name = "Ali" # String
pi = 3.14 # Float
flag = True # Boolean
📌 5. Input
Get user input.
name = input("Enter your name: ")
print("Hello", name)
📌 6. Data Types and Casting
int("10") # Converts string to integer
str(123) # Converts integer to string
float("3.14") # Converts string to float
📌 7. Conditional Statements
x = 10
if x > 5:
print("Greater")
elif x == 5:
print("Equal")
else:
print("Smaller")
📌 8. Loops
🔹 for Loop
for i in range(5):
print(i) # Prints 0 to 4
🔹 while Loop
i = 0
while i < 5:
print(i)
i += 1
📌 9. Functions
def greet(name):
print("Hello", name)
greet("Aisha")
📌 10. Operators
# Arithmetic operators
+ - * / % ** //
# Comparison operators
== != > < >= <=
# Logical operators
and or not
📌 11. Lists, Tuples, Dictionaries, Sets
# List
fruits = ["apple", "banana", "cherry"]
# Tuple
coordinates = (10, 20)
# Dictionary
student = {"name": "Ali", "age": 20}
# Set
colors = {"red", "green", "blue"}
📌 12. List Example
fruits = ["apple", "banana"]
fruits.append("mango")
print(fruits[1]) # banana
📝 Python Variables
🧠 What Are Variables in Python?
A variable is like a container that holds data. It stores values you want to use in your program.
🔹 1. Declaring a Variable
Python does not require you to declare the type of variable. Just assign a value using =.
x = 5 # Integer
name = "Alice" # String
price = 19.99 # Float
is_valid = True # Boolean
🔹 2. Variable Naming Rules
✅ Valid names:
- Start with a letter or underscore _
- Followed by letters, digits, or underscores
- Case-sensitive (name and Name are different)
❌ Invalid names:
2name = "Ali" # ❌ Cannot start with a digit
user-name = "Ali" # ❌ Hyphens not allowed
✅ Valid examples:
user_name = "Ali"
_user = "hidden"
Name1 = "John"
🔹 3. Data Types Stored in Variables
integer = 42
float_num = 3.14
string = "Hello"
boolean = True
list_var = [1, 2, 3]
dict_var = {"key": "value"}
🔹 4. Checking the Type of a Variable
x = 10
print(type(x)) # Output: <class 'int'>
🔹 5. Multiple Assignments
You can assign multiple variables at once:
a, b, c = 1, 2, 3
print(a, b, c) # Output: 1 2 3
# Assigning the same value to multiple variables:
x = y = z = 0
🔹 6. Constants (By Convention)
Python doesn't have true constants, but you can use uppercase names to indicate a value shouldn't change.
PI = 3.14159
MAX_USERS = 100
🔒 These can still be changed in code, but shouldn't be.
🔹 7. Type Casting (Changing Variable Types)
x = str(10) # '10'
y = int("5") # 5
z = float("3.14") # 3.14
🔹 8. Deleting a Variable
x = 10
del x
Trying to use x after this will give an error.
🧠 What Are Data Types in Python?
A data type tells Python what kind of value a variable holds. For example:
- "Ali" is a string
- 10 is an integer
- 3.14 is a float
- True is a boolean
Python automatically assigns the correct type when you assign a value to a variable.
🔹 1. Basic (Built-in) Data Types
🔸 int – Integer
a = 100
print(type(a)) # <class 'int'>
🔸 float – Decimal / Floating Point
pi = 3.14159
print(type(pi)) # <class 'float'>
🔸 str – String
name = "Alice"
print(type(name)) # <class 'str'>
🔸 bool – Boolean
is_online = True
print(type(is_online)) # <class 'bool'>
🔹 2. Collection Data Types
🔸 list – Mutable Sequence
fruits = ["apple", "banana", "cherry"]
print(type(fruits)) # <class 'list'>
🔸 tuple – Immutable Sequence
point = (10, 20)
print(type(point)) # <class 'tuple'>
🔸 set – Unique, Unordered Collection
colors = {"red", "green", "blue"}
print(type(colors)) # <class 'set'>
🔸 dict – Dictionary (Key:Value Pairs)
student = {"name": "Ali", "age": 21}
print(type(student)) # <class 'dict'>
🔹 3. None Type
Represents the absence of a value.
x = None
print(type(x)) # <class 'NoneType'>
🔹 4. Type Conversion (Casting)
Convert one type into another:
int("10") # 10
str(99) # "99"
float("3.14") # 3.14
bool(1) # True
🔹 5. Checking the Type
a = 10
print(type(a)) # <class 'int'>
🔢 Python Numbers
In Python, numbers are a built-in data type used to store numeric values. There are three main numeric types:
🔹 1. Integer (int)
Whole numbers without decimals. Can be positive or negative.
a = 100
b = -25
print(type(a)) # <class 'int'>
🔹 2. Float (float)
Numbers with decimal points. Used for measurements, prices, etc.
pi = 3.14159
temperature = -5.5
print(type(pi)) # <class 'float'>
🔹 3. Complex (complex)
Numbers with a real and imaginary part (a + bj). j is the imaginary unit in Python (like i in math).
z = 2 + 3j
print(type(z)) # <class 'complex'>
🔸 4. Type Conversion (Casting)
You can convert between number types using:
int(3.9) # 3
float(5) # 5.0
complex(4) # (4+0j)
🔸 5. Number Operations
Python supports arithmetic operations:
a = 15
b = 4
print(f"Addition: {a + b}") # 19
print(f"Subtraction: {a - b}") # 11
print(f"Multiplication: {a * b}") # 60
print(f"Division: {a / b}") # 3.75
print(f"Floor division: {a // b}") # 3
print(f"Modulus: {a % b}") # 3
print(f"Exponentiation: {a ** b}") # 50625
🔸 6. Built-in Number Functions
x = -5.7
print(abs(x)) # 5.7 (absolute value)
print(round(x)) # -6 (round to nearest integer)
print(max(1, 2, 3)) # 3 (maximum value)
print(min(1, 2, 3)) # 1 (minimum value)
print(pow(2, 3)) # 8 (2 to the power of 3)
🔸 7. Using the math Module
Python's math module gives you access to advanced mathematical functions:
import math
print(math.sqrt(16)) # 4.0
print(math.factorial(5)) # 120
print(math.pi) # 3.141592...
print(math.ceil(2.3)) # 3
print(math.floor(2.7)) # 2
🔄 What is Python Casting?
Casting means converting a value from one data type to another. Python provides built-in functions to perform casting between:
- int → integer
- float → decimal
- str → string
- bool → boolean
✅ Python does automatic casting sometimes, but you can also manually cast using functions.
🔹 1. Casting to int
Used to convert float or string to an integer. It removes the decimal part.
x = int(3.9) # 3
y = int("10") # 10
z = int(True) # 1
# Invalid
# int("hello") → Error
🔹 2. Casting to float
Used to convert int or string to a float (decimal).
a = float(5) # 5.0
b = float("7.25") # 7.25
c = float(False) # 0.0
🔹 3. Casting to str
Used to convert any type (int, float, bool) into a string.
name = str(123) # "123"
price = str(99.99) # "99.99"
flag = str(True) # "True"
🔹 4. Casting to bool
Used to convert values to True or False:
print(bool(1)) # True
print(bool(0)) # False
print(bool("hi")) # True
print(bool("")) # False
🔸 5. Common Mistakes in Casting
int("3.5") # ❌ Error (you must use float first)
float("abc") # ❌ Error (can't convert letters to numbers)
int("five") # ❌ Error (not a number string)
# ✅ For example:
x = int(float("3.5")) # ✅ 3
🔹 6. Automatic Type Conversion (Implicit)
Python sometimes converts types automatically:
x = 5 # int
y = 2.0 # float
result = x + y # Result will be float (7.0)
print(result) # 7.0
📋 Python Lists
🎯 Understanding Lists
Lists are one of the most fundamental and versatile data structures in Python. They are ordered, mutable collections that can store multiple items of different types. Think of a list as a container that holds items in a specific order, where you can add, remove, or modify items as needed.
📊 Characteristics
- Ordered: Items maintain their position
- Mutable: Can be changed after creation
- Allow duplicates: Same value can appear multiple times
- Mixed types: Can store different data types
🎪 Common Uses
- Storing collections of data
- Managing to-do items
- Keeping track of scores or measurements
- Building dynamic data structures
🎯 Creating Lists
There are several ways to create lists in Python:
# Creating lists with initial values
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = ["hello", 42, True, 3.14]
# Empty list
empty_list = []
also_empty = list()
# List with repeated values
zeros = [0] * 5 # [0, 0, 0, 0, 0]
# List from range
countdown = list(range(10, 0, -1)) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
# List from string
letters = list("Python") # ['P', 'y', 't', 'h', 'o', 'n']
print(f"Fruits: {fruits}")
print(f"Mixed types: {mixed}")
print(f"Countdown: {countdown}")
🔍 Accessing List Elements
Lists use zero-based indexing, meaning the first item is at index 0:
colors = ["red", "green", "blue", "yellow", "purple"]
# Positive indexing (from start)
print(colors[0]) # "red" - first item
print(colors[2]) # "blue" - third item
print(colors[4]) # "purple" - last item
# Negative indexing (from end)
print(colors[-1]) # "purple" - last item
print(colors[-2]) # "yellow" - second to last
# List slicing
print(colors[1:4]) # ["green", "blue", "yellow"] - items 1 to 3
print(colors[:3]) # ["red", "green", "blue"] - first 3 items
print(colors[2:]) # ["blue", "yellow", "purple"] - from index 2 to end
print(colors[::2]) # ["red", "blue", "purple"] - every 2nd item
print(colors[::-1]) # Reverse the list
# Getting list length
print(f"List has {len(colors)} items")
➕ Adding Items to Lists
Python provides several methods to add items to lists:
shopping_list = ["milk", "bread"]
# append() - Add single item to end
shopping_list.append("eggs")
print(f"After append: {shopping_list}")
# insert() - Add item at specific position
shopping_list.insert(1, "butter") # Insert at index 1
print(f"After insert: {shopping_list}")
# extend() - Add multiple items from another list
more_items = ["cheese", "yogurt", "honey"]
shopping_list.extend(more_items)
print(f"After extend: {shopping_list}")
# Using + operator to combine lists
fruits = ["apple", "banana"]
vegetables = ["carrot", "lettuce"]
grocery = fruits + vegetables
print(f"Combined list: {grocery}")
# Using += to add to existing list
fruits += ["orange", "grape"]
print(f"Updated fruits: {fruits}")
➖ Removing Items from Lists
Multiple ways to remove items from lists:
numbers = [1, 2, 3, 4, 5, 3, 6]
# remove() - Remove first occurrence of value
numbers.remove(3) # Removes first 3
print(f"After remove(3): {numbers}")
# pop() - Remove and return item by index
last_item = numbers.pop() # Remove last item
print(f"Popped item: {last_item}, List: {numbers}")
second_item = numbers.pop(1) # Remove item at index 1
print(f"Popped item: {second_item}, List: {numbers}")
# del - Delete by index or slice
del numbers[0] # Delete first item
print(f"After del[0]: {numbers}")
# clear() - Remove all items
backup = numbers.copy() # Make a backup first
numbers.clear()
print(f"After clear(): {numbers}")
print(f"Backup: {backup}")
🔧 Modifying and Organizing Lists
Change, sort, and organize your list data:
scores = [85, 92, 78, 96, 88]
# Modifying individual items
scores[2] = 82 # Change third score
print(f"Updated scores: {scores}")
# Modifying multiple items with slicing
scores[1:3] = [95, 85] # Replace items at index 1 and 2
print(f"After slice modification: {scores}")
# Sorting
names = ["Charlie", "Alice", "Bob", "Diana"]
names.sort() # Sort in place (alphabetical)
print(f"Sorted names: {names}")
# Sort in reverse
scores.sort(reverse=True)
print(f"Scores (highest first): {scores}")
# sorted() - Returns new sorted list without changing original
original = [3, 1, 4, 1, 5]
sorted_version = sorted(original)
print(f"Original: {original}")
print(f"Sorted copy: {sorted_version}")
# reverse() - Reverse the order
colors = ["red", "green", "blue"]
colors.reverse()
print(f"Reversed colors: {colors}")
# Counting and finding
letters = ['a', 'b', 'a', 'c', 'a', 'b']
print(f"Count of 'a': {letters.count('a')}")
print(f"Index of 'b': {letters.index('b')}")
🔍 List Comprehensions
Create new lists in a concise and readable way:
# Basic list comprehension
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(f"Squares: {squares}")
# With condition
even_squares = [x**2 for x in numbers if x % 2 == 0]
print(f"Even squares: {even_squares}")
# String manipulation
words = ["hello", "world", "python", "programming"]
capitalized = [word.upper() for word in words]
long_words = [word for word in words if len(word) > 5]
print(f"Capitalized: {capitalized}")
print(f"Long words: {long_words}")
# Nested loops in comprehension
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(f"Flattened matrix: {flattened}")
# Creating a multiplication table
multiplication_table = [[i * j for j in range(1, 6)] for i in range(1, 6)]
for row in multiplication_table:
print(row)
🎪 Advanced List Operations
Powerful techniques for working with lists:
# Copying lists
original = [1, 2, 3, 4, 5]
shallow_copy = original.copy()
deep_copy = original[:]
# Checking membership
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("orange" not in fruits) # True
# Unpacking lists
coordinates = [10, 20, 30]
x, y, z = coordinates
print(f"x={x}, y={y}, z={z}")
# Using * for flexible unpacking
numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers
print(f"First: {first}, Middle: {middle}, Last: {last}")
# zip() - Combine multiple lists
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["New York", "London", "Tokyo"]
combined = list(zip(names, ages, cities))
print("Combined data:")
for name, age, city in combined:
print(f" {name}, {age} years old, lives in {city}")
# enumerate() - Get index and value
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# max(), min(), sum() with lists
numbers = [4, 2, 9, 1, 7]
print(f"Max: {max(numbers)}")
print(f"Min: {min(numbers)}")
print(f"Sum: {sum(numbers)}")
print(f"Average: {sum(numbers) / len(numbers)}")
🎯 Practical List Examples
Real-world applications of lists:
# Student grade management
class GradeBook:
def __init__(self):
self.grades = []
def add_grade(self, grade):
if 0 <= grade <= 100:
self.grades.append(grade)
print(f"Added grade: {grade}")
else:
print("Grade must be between 0 and 100")
def get_average(self):
if self.grades:
return sum(self.grades) / len(self.grades)
return 0
def get_letter_grade(self):
avg = self.get_average()
if avg >= 90: return 'A'
elif avg >= 80: return 'B'
elif avg >= 70: return 'C'
elif avg >= 60: return 'D'
else: return 'F'
# Usage example
student_grades = GradeBook()
student_grades.add_grade(85)
student_grades.add_grade(92)
student_grades.add_grade(78)
print(f"Average: {student_grades.get_average():.1f}")
print(f"Letter Grade: {student_grades.get_letter_grade()}")
# Inventory management
inventory = [
{"item": "Laptop", "quantity": 5, "price": 999.99},
{"item": "Mouse", "quantity": 20, "price": 25.99},
{"item": "Keyboard", "quantity": 15, "price": 79.99}
]
# Find total inventory value
total_value = sum(item["quantity"] * item["price"] for item in inventory)
print(f"Total inventory value: ${total_value:.2f}")
# Find items running low (quantity < 10)
low_stock = [item["item"] for item in inventory if item["quantity"] < 10]
print(f"Low stock items: {low_stock}")
🏋️ Practice: List Mastery
📚 Quick Reference
my_list = [1, 2, 3]
- With initial valuesempty = []
- Empty listrepeated = [0] * 5
- Repeated valuesfrom_range = list(range(1, 6))
- From range
list.append(item)
- Add to endlist.insert(index, item)
- Insert at positionlist.extend(other_list)
- Add multiple itemslist1 + list2
- Combine lists
list.remove(value)
- Remove by valuelist.pop(index)
- Remove by indexdel list[index]
- Delete by indexlist.clear()
- Remove all items
len(list)
- Get lengthitem in list
- Check membershiplist.count(item)
- Count occurrenceslist.index(item)
- Find indexlist.sort()
- Sort in placesorted(list)
- Return sorted copy
📚 Python Dictionaries
Creating Dictionaries
Dictionaries store data in key-value pairs and are unordered, changeable, and indexed:
🗝️ Dictionary Basics
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
print(person["name"]) # Access by key
print(person.get("age")) # Safe access with get()
# Adding new key-value pairs
person["job"] = "Engineer"
print(person)
Dictionary Methods
🔧 Dictionary Operations
student = {"name": "Bob", "grade": "A", "age": 20}
# Get all keys, values, or items
keys = student.keys()
values = student.values()
items = student.items()
# Update dictionary
student.update({"subject": "Math", "score": 95})
# Remove items
removed = student.pop("age") # Remove and return value
del student["grade"] # Remove key-value pair
print(student)
Practice: Dictionary Operations
📦 Python Tuples
🔒 Immutable Collections
Tuples are ordered and unchangeable collections. They allow duplicate values:
coordinates = (10, 20)
colors = ("red", "green", "blue")
# Accessing tuple items
print(coordinates[0]) # First item
print(colors[-1]) # Last item
# Tuples are immutable - this would cause an error:
# coordinates[0] = 15
# Tuple unpacking
x, y = coordinates
print(f"X: {x}, Y: {y}")
# Multiple assignment
point = (5, 10, 15)
x, y, z = point
⚡ When to Use Tuples
Use tuples for data that shouldn't change:
# RGB color values
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# Geographic coordinates
locations = [
("Paris", 48.8566, 2.3522),
("London", 51.5074, -0.1278),
("Tokyo", 35.6762, 139.6503)
]
for city, lat, lon in locations:
print(f"{city}: {lat}, {lon}")
Practice: Working with Tuples
🎯 Python Sets
🔍 Unique Collections
Sets are unordered collections of unique items:
fruits = {"apple", "banana", "cherry"}
numbers = {1, 2, 3, 4, 5}
# Sets automatically remove duplicates
duplicates = {1, 2, 2, 3, 3, 4}
print(duplicates) # {1, 2, 3, 4}
# Adding and removing items
fruits.add("orange")
fruits.remove("banana") # Error if item doesn't exist
fruits.discard("grape") # No error if item doesn't exist
print(fruits)
🧮 Set Operations
Sets support mathematical operations like union, intersection, and difference:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# Union - all unique items from both sets
union = set1 | set2 # or set1.union(set2)
# Intersection - items in both sets
intersection = set1 & set2 # or set1.intersection(set2)
# Difference - items in set1 but not in set2
difference = set1 - set2 # or set1.difference(set2)
print(f"Union: {union}")
print(f"Intersection: {intersection}")
print(f"Difference: {difference}")
Practice: Set Operations
🎯 If...Else Statements
🔀 Basic Conditional Logic
Python supports conditional statements that allow you to make decisions in your code:
age = 18
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
# Using elif for multiple conditions
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Your grade is: {grade}")
🧮 Comparison and Logical Operators
Use comparison and logical operators to create complex conditions:
temperature = 25
is_sunny = True
# Comparison operators: ==, !=, <, >, <=, >=
if temperature > 20:
print("It's warm!")
# Logical operators: and, or, not
if temperature > 20 and is_sunny:
print("Perfect weather for a picnic!")
if temperature < 0 or temperature > 35:
print("Extreme weather!")
if not is_sunny:
print("Bring an umbrella!")
# Checking membership with 'in'
fruits = ["apple", "banana", "cherry"]
if "apple" in fruits:
print("Apple is available!")
Practice: Conditional Logic
🔄 While Loops
🎯 Understanding While Loops
While loops repeatedly execute a block of code as long as a specified condition remains true. They're perfect for situations where you don't know exactly how many times you need to repeat something, but you know when to stop.
When to use while loops:
- When the number of iterations is unknown beforehand
- When you need to repeat until a specific condition is met
- For user input validation and menu systems
- For processing data until a sentinel value is encountered
🎯 Basic While Loop
While loops repeat a block of code as long as a condition is true:
# Simple countdown
count = 5
while count > 0:
number = 0
while number < 10:
number += 1
if number % 2 == 0:
continue # Skip even numbers
print(f"Odd number: {number}")
Practice: While Loops
🔁 For Loops
🎯 Basic For Loops
For loops iterate over sequences like lists, strings, or ranges:
# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
# Loop through a string
for letter in "Hello":
print(letter)
# Loop with range
for i in range(5):
print(f"Number: {i}")
# Range with start and end
for i in range(1, 6):
print(f"Count: {i}")
# Range with step
for i in range(0, 10, 2):
print(f"Even: {i}")
🔢 Advanced For Loop Techniques
# Loop with index using enumerate
shopping_list = ["milk", "bread", "eggs", "cheese"]
for index, item in enumerate(shopping_list):
print(f"{index + 1}. {item}")
# Iterating over dictionary
student_grades = {"Alice": 85, "Bob": 90, "Charlie": 78}
for name, grade in student_grades.items():
print(f"{name}: {grade}")
# Nested loops - multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i * j}")
print("---")
# List comprehension alternative
squares = [x**2 for x in range(1, 6)]
print(f"Squares: {squares}")
# Using zip to iterate over multiple lists
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
Practice: For Loops
🎯 Python Functions
🔧 Defining Functions
Functions are reusable blocks of code that perform specific tasks:
# Simple function
def greet():
print("Hello, World!")
greet() # Call the function
# Function with parameters
def greet_person(name):
print(f"Hello, {name}!")
greet_person("Alice")
# Function with return value
def add_numbers(a, b):
result = a + b
return result
sum_result = add_numbers(5, 3)
print(f"Sum: {sum_result}")
# Function with multiple parameters and return
def calculate_area(length, width):
area = length * width
return area
room_area = calculate_area(10, 12)
print(f"Room area: {room_area} square feet")
🎨 Function Examples
# Function with default parameters
def introduce(name, age=25, city="Unknown"):
print(f"Hi, I'm {name}, {age} years old, from {city}")
introduce("Alice") # Uses defaults
introduce("Bob", 30) # Overrides age
introduce("Charlie", city="Paris") # Uses keyword argument
# Function returning multiple values
def get_name_parts(full_name):
parts = full_name.split()
first_name = parts[0]
last_name = parts[-1] if len(parts) > 1 else ""
return first_name, last_name
first, last = get_name_parts("Alice Johnson")
print(f"First: {first}, Last: {last}")
# Function with docstring
def fahrenheit_to_celsius(fahrenheit):
"""
Convert temperature from Fahrenheit to Celsius.
Args:
fahrenheit (float): Temperature in Fahrenheit
Returns:
float: Temperature in Celsius
"""
celsius = (fahrenheit - 32) * 5/9
return celsius
temp = fahrenheit_to_celsius(100)
print(f"100°F = {temp:.1f}°C")
Practice: Functions
📦 Function Arguments
🎯 Different Types of Arguments
Python functions support various types of arguments:
# Positional arguments
def introduce(name, age, city):
print(f"Hi, I'm {name}, {age} years old, from {city}")
introduce("Alice", 25, "New York")
# Keyword arguments
introduce(city="London", name="Bob", age=30)
# *args - variable number of positional arguments
def sum_all(*numbers):
total = 0
for num in numbers:
total += num
return total
print(sum_all(1, 2, 3)) # 6
print(sum_all(1, 2, 3, 4, 5)) # 15
# **kwargs - variable number of keyword arguments
def create_profile(**info):
print("User Profile:")
for key, value in info.items():
print(f" {key}: {value}")
create_profile(name="Alice", age=25, job="Engineer", city="Boston")
🎨 Combining Argument Types
# Combining different argument types
def complex_function(required, default="default", *args, **kwargs):
print(f"Required: {required}")
print(f"Default: {default}")
print(f"Args: {args}")
print(f"Kwargs: {kwargs}")
complex_function("hello")
complex_function("hello", "world", 1, 2, 3, name="Alice", age=25)
# Lambda functions (anonymous functions)
square = lambda x: x**2
add = lambda x, y: x + y
print(square(5)) # 25
print(add(3, 4)) # 7
# Using lambda with built-in functions
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Squared: {squared}")
print(f"Even: {even_numbers}")
Practice: Function Arguments
🌐 Variable Scope
🎯 Understanding Scope
Scope determines where variables can be accessed in your code:
# Global scope
global_var = "I'm global"
def my_function():
# Local scope
local_var = "I'm local"
print(f"Inside function: {global_var}") # Can access global
print(f"Inside function: {local_var}") # Can access local
my_function()
print(f"Outside function: {global_var}") # Can access global
# print(local_var) # This would cause an error!
# Modifying global variables
counter = 0
def increment():
global counter # Tell Python we want to modify the global variable
counter += 1
print(f"Counter: {counter}")
increment() # Counter: 1
increment() # Counter: 2
print(f"Final counter: {counter}") # Final counter: 2
🔗 LEGB Rule
Python follows the LEGB rule for variable lookup: Local → Enclosing → Global → Built-in
# Built-in scope (like len, print, etc.)
# Global scope
x = "global x"
def outer_function():
# Enclosing scope
x = "enclosing x"
def inner_function():
# Local scope
x = "local x"
print(f"Inner function: {x}") # local x
inner_function()
print(f"Outer function: {x}") # enclosing x
outer_function()
print(f"Global scope: {x}") # global x
# Nonlocal keyword
def outer():
x = "outer x"
def inner():
nonlocal x # Modify the enclosing scope variable
x = "modified by inner"
print(f"Inner: {x}")
inner()
print(f"Outer after inner: {x}")
outer()
Practice: Variable Scope
📦 Python Modules
🧩 Understanding Modules
Modules are Python files containing definitions and statements that can be imported and used in other Python programs:
# Import entire module
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
print(math.cos(0)) # 1.0
# Import with alias
import datetime as dt
now = dt.datetime.now()
print(f"Current time: {now}")
# Import specific functions
from random import randint, choice
number = randint(1, 100) # Random integer between 1-100
color = choice(['red', 'blue', 'green']) # Random choice from list
print(f"Random number: {number}, Random color: {color}")
# Import all (use with caution)
from math import *
result = sin(pi/2) # Now we can use sin and pi directly
print(f"sin(π/2) = {result}")
📚 Popular Standard Library Modules
# datetime - Working with dates and times
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)
print(f"Today: {now.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"Tomorrow: {tomorrow.strftime('%Y-%m-%d')}")
# random - Generate random numbers and choices
import random
print(f"Random integer: {random.randint(1, 100)}")
print(f"Random float: {random.random()}")
colors = ['red', 'green', 'blue', 'yellow']
random.shuffle(colors)
print(f"Shuffled colors: {colors}")
# os - Operating system interface
import os
print(f"Current directory: {os.getcwd()}")
# json - Working with JSON data
import json
data = {"name": "Alice", "age": 30, "city": "New York"}
json_string = json.dumps(data)
parsed_data = json.loads(json_string)
print(f"JSON: {json_string}")
print(f"Parsed name: {parsed_data['name']}")
🔧 Creating Your Own Modules
You can create your own modules by saving functions in a .py file:
# File: calculator.py (your custom module)
"""
A simple calculator module
"""
PI = 3.14159
AUTHOR = "Your Name"
def add(x, y):
"""Add two numbers"""
return x + y
def multiply(x, y):
"""Multiply two numbers"""
return x * y
def circle_area(radius):
"""Calculate area of a circle"""
return PI * radius * radius
class Calculator:
def __init__(self):
self.history = []
def calculate(self, operation, x, y):
if operation == '+':
result = add(x, y)
elif operation == '*':
result = multiply(x, y)
else:
result = None
self.history.append(f"{x} {operation} {y} = {result}")
return result
# This runs only when the file is executed directly
if __name__ == "__main__":
print("Testing calculator module...")
print(f"5 + 3 = {add(5, 3)}")
print(f"Circle area (radius=5): {circle_area(5)}")
# Now you can use your custom module in another file:
# import calculator
# result = calculator.add(10, 5)
# print(f"Addition result: {result}")
Practice: Using Modules
⚠️ Exception Handling
🛡️ Basic Try and Except
Exception handling allows you to gracefully handle errors in your code:
# Basic exception handling
try:
# Code that might raise an exception
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result: {result}")
except ZeroDivisionError:
# Handle specific exception
print("Error: Cannot divide by zero!")
except ValueError:
# Handle another specific exception
print("Error: Please enter a valid number!")
print("Program continues executing...")
# Multiple exceptions in one except block
try:
age = int(input("Enter your age: "))
print(f"Next year you'll be {age + 1}")
except (ValueError, TypeError):
print("Please enter a valid age!")
🔧 Advanced Exception Handling
# Try-except-else-finally
def divide_numbers(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero!")
return None
except TypeError:
print("Invalid input types!")
return None
else:
# Runs only if no exception occurred
print("Division successful!")
return result
finally:
# Always runs, regardless of exceptions
print("Division operation completed")
print(divide_numbers(10, 2)) # Normal case
print(divide_numbers(10, 0)) # Zero division
print(divide_numbers("10", 2)) # Type error
# Raising custom exceptions
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
if age > 150:
raise ValueError("Age seems unrealistic!")
return True
try:
validate_age(-5)
except ValueError as e:
print(f"Validation error: {e}")
📋 Common Exception Types
# Different types of exceptions
examples = [
# IndexError
lambda: [1, 2, 3][5],
# KeyError
lambda: {"name": "Alice"}["age"],
# AttributeError
lambda: "hello".append("world"),
# FileNotFoundError
lambda: open("nonexistent.txt"),
# TypeError
lambda: "5" + 5
]
exception_names = ["IndexError", "KeyError", "AttributeError",
"FileNotFoundError", "TypeError"]
for i, example in enumerate(examples):
try:
example()
except Exception as e:
print(f"{exception_names[i]}: {e}")
# Generic exception handling (use sparingly)
try:
# Some risky operation
result = some_dangerous_function()
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Log the error for debugging
import traceback
traceback.print_exc()
Practice: Exception Handling
🚀 Practice Projects
🔢 Project 1: Calculator
Build a simple calculator that can add, subtract, multiply, and divide:
# Simple calculator project
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y != 0:
return x / y
else:
return "Cannot divide by zero!"
def calculator():
print("Welcome to Simple Calculator!")
print("Operations: +, -, *, /")
while True:
try:
num1 = float(input("Enter first number: "))
operation = input("Enter operation (+, -, *, /) or 'quit': ")
if operation.lower() == 'quit':
break
num2 = float(input("Enter second number: "))
if operation == '+':
result = add(num1, num2)
elif operation == '-':
result = subtract(num1, num2)
elif operation == '*':
result = multiply(num1, num2)
elif operation == '/':
result = divide(num1, num2)
else:
print("Invalid operation!")
continue
print(f"Result: {result}")
except ValueError:
print("Please enter valid numbers!")
# calculator() # Uncomment to run
📝 Project 2: To-Do List
Create a command-line to-do list application:
# To-Do list project
class TodoList:
def __init__(self):
self.tasks = []
def add_task(self, task):
self.tasks.append({"task": task, "completed": False})
print(f"Added: '{task}'")
def show_tasks(self):
if not self.tasks:
print("No tasks yet!")
return
print("\nYour Tasks:")
for i, task in enumerate(self.tasks, 1):
status = "✓" if task["completed"] else "○"
print(f"{i}. {status} {task['task']}")
def complete_task(self, index):
if 1 <= index <= len(self.tasks):
self.tasks[index - 1]["completed"] = True
print(f"Completed: '{self.tasks[index - 1]['task']}'")
else:
print("Invalid task number!")
def remove_task(self, index):
if 1 <= index <= len(self.tasks):
removed = self.tasks.pop(index - 1)
print(f"Removed: '{removed['task']}'")
else:
print("Invalid task number!")
# Example usage
todo = TodoList()
todo.add_task("Learn Python")
todo.add_task("Build a project")
todo.add_task("Practice coding")
todo.show_tasks()
todo.complete_task(1)
todo.show_tasks()
🎯 Project 3: Number Guessing Game
Create an interactive number guessing game:
# Number guessing game
import random
def guessing_game():
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100")
# Generate random number
secret_number = random.randint(1, 100)
attempts = 0
max_attempts = 7
while attempts < max_attempts:
try:
guess = int(input(f"\nAttempt {attempts + 1}/{max_attempts} - Enter your guess: "))
attempts += 1
if guess == secret_number:
print(f"🎉 Congratulations! You guessed it in {attempts} attempts!")
break
elif guess < secret_number:
print("Too low! Try higher.")
else:
print("Too high! Try lower.")
# Give hints
if attempts == max_attempts // 2:
if secret_number % 2 == 0:
print("Hint: The number is even!")
else:
print("Hint: The number is odd!")
except ValueError:
print("Please enter a valid number!")
attempts -= 1 # Don't count invalid input as an attempt
else:
print(f"Game over! The number was {secret_number}")
# Ask to play again
play_again = input("Play again? (y/n): ").lower()
if play_again == 'y':
guessing_game()
# guessing_game() # Uncomment to run
📝 Python Comments
✅ What is a Comment?
A comment is a line in your code that Python ignores during execution. It is used to:
🔹 1. Single-Line Comments
Use the # symbol. Everything after # on that line is ignored by Python.
🔹 2. Multi-Line Comments (Docstrings or Block Comments)
Python doesn't have official multi-line comments, but you can:
Method 1: Use multiple #
Method 2: Use triple quotes (''' or """)
(These are technically multi-line strings, often used for documentation.)
💡 Triple quotes are mainly used for docstrings in functions, classes, and modules.
🔹 3. Docstrings (Documentation Strings)
A docstring is a special kind of comment used to describe a function, class, or module. It goes right after the def, class, or top of a file.
🧠 Why Use Comments?
🚫 What Not to Do with Comments
Don't over-comment obvious code:
Don't use comments to justify bad code. Instead, refactor the code.