Python Programming
Comprehensive Revision Notes: Basics to Advanced
1. Python Basics
Variables & Data Types
Python is dynamically typed. You don't need to declare types explicitly. Core types include integers,
floats, strings, and booleans.
# Variable assignment
name = "Alice" # str
age = 25 # int
height = 5.5 # float
is_student = True # bool
# Type casting
age_str = str(age) # Converts int to str
pi_int = int(3.14) # Converts float to int (Result: 3)
Operators
Used to perform operations on variables and values.
• Arithmetic: + , - , * , / , // (floor division), % (modulo), ** (exponent)
• Comparison: == , != , > , < , >= , <=
• Logical: and , or , not
2. Control Flow
Conditional Statements (If-Elif-Else)
Controls the flow of execution based on conditions.
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 80:
print("Grade: B")
else:
print("Grade: C")
Loops (For & While)
Loops are used to iterate over sequences or execute code until a condition is met.
# For Loop (Iterating over a range)
for i in range(3):
print(i) # Prints 0, 1, 2
# While Loop
count = 0
while count < 3:
print(count)
count += 1
# Loop Control: break (exits loop) and continue (skips to next iteration)
3. Data Structures
Lists
Ordered, mutable (changeable) collections of items.
fruits = ["apple", "banana", "cherry"]
[Link]("orange") # Adds to the end
[Link](1, "mango") # Inserts at index 1
print(fruits[0]) # Accessing: "apple"
Tuples
Ordered, immutable collections. Faster than lists.
coordinates = (10.0, 20.0)
# coordinates[0] = 15.0 # Error! Tuples cannot be modified
Sets
Unordered collections of unique elements. Great for removing duplicates.
unique_numbers = {1, 2, 2, 3}
print(unique_numbers) # Output: {1, 2, 3}
Dictionaries
Collections of key-value pairs. Keys must be unique and immutable.
student = {"name": "John", "age": 20}
student["grade"] = "A" # Adding a new key-value pair
print(student["name"]) # Output: John
for key, value in [Link]():
print(f"{key}: {value}")
4. Functions
Defining Functions
Blocks of reusable code defined using the def keyword.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Alice")) # Output: Hello, Alice!
print(greet("Bob", "Welcome")) # Output: Welcome, Bob!
*args and **kwargs
Used to pass a variable number of arguments to a function.
def add_numbers(*args):
return sum(args) # args is a tuple of all positional arguments
def print_info(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}") # kwargs is a dict of keyword arguments
Lambda Functions
Small anonymous functions written in a single line.
square = lambda x: x ** 2
print(square(5)) # Output: 25
5. Error & Exception Handling
Prevents the program from crashing when an error occurs.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
print("This block always executes, regardless of errors.")
6. File Handling
Using context managers ( with ) ensures the file is automatically closed after operations.
# Writing to a file
with open("[Link]", "w") as file:
[Link]("Hello World!
")
# Reading from a file
with open("[Link]", "r") as file:
content = [Link]()
print(content)
7. Object-Oriented Programming (OOP)
Classes and Objects
A class is a blueprint, and an object is an instance of a class. __init__ is the constructor.
class Dog:
def __init__(self, name, age):
[Link] = name # Attribute
[Link] = age
def bark(self): # Method
return f"{[Link]} says Woof!"
my_dog = Dog("Buddy", 3)
print(my_dog.bark())
Inheritance
A class can inherit attributes and methods from another class.
class Animal:
def speak(self):
return "Animal sound"
class Cat(Animal): # Cat inherits from Animal
def speak(self): # Method overriding (Polymorphism)
return "Meow"
my_cat = Cat()
print(my_cat.speak()) # Output: Meow
8. Advanced Python Concepts
Comprehensions
A concise way to create lists, dictionaries, or sets.
# List Comprehension
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
# Dictionary Comprehension
sq_dict = {x: x**2 for x in range(3)} # {0: 0, 1: 1, 2: 4}
Generators
Functions that yield values one at a time instead of returning a whole list. They are highly
memory-efficient.
def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
counter = count_up_to(3)
print(next(counter)) # 1
print(next(counter)) # 2
Decorators
Functions that modify the behavior of another function without changing its source code.
def my_decorator(func):
def wrapper():
print("Before the function runs.")
func()
print("After the function runs.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()