Python
Python
Iterators
Definition: An object in Python that implements the iterator protocol with __iter__() and __next__()
methods.
Example:
python
CopyEdit
nums = [1, 2, 3]
it = iter(nums)
print(next(it)) # Output: 1
print(next(it)) # Output: 2
Explanation: iter() returns an iterator object; next() fetches the next item. for loops use this protocol
internally.
2. Generators
Definition: A function that uses yield to return a sequence of values lazily (on demand), saving
memory.
Example:
python
CopyEdit
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
print(i)
Explanation: yield pauses function state and resumes on next iteration, useful for large or infinite
sequences.
Definition:
• Module: A .py file containing Python code.
Example:
python
CopyEdit
# file: math_utils.py
def square(x):
return x * x
# main.py
import math_utils
print(math_utils.square(4)) # Output: 16
4. List Comprehensions
Definition: A concise way to create lists using for loops and optional if conditions.
Example:
python
CopyEdit
5. Regular Expressions
Definition: A powerful tool for pattern matching and text processing using the re module.
Example:
python
CopyEdit
import re
pattern = r"\d{3}-\d{2}-\d{4}"
Explanation: \d{3} matches exactly 3 digits; useful for extracting patterns like dates, emails, or IDs.
6. Serialization (Pickle)
Definition: Converting Python objects into byte streams using pickle for saving or transferring.
Example:
python
CopyEdit
import pickle
pickle.dump(data, f)
# Load back
restored = pickle.load(f)
Explanation: Saves and retrieves complex objects like dictionaries between sessions.
7. Partial Functions
Definition: Fixes some arguments of a function using functools.partial, creating a new callable.
Example:
python
CopyEdit
8. Closures
Definition: A function defined inside another that remembers variables from the enclosing scope.
Example:
python
CopyEdit
def outer(x):
def inner(y):
return x + y
return inner
add10 = outer(10)
print(add10(5)) # Output: 15
Explanation: inner retains access to x even after outer has finished execution.
9. Decorators
Definition: Functions that modify the behavior of other functions without changing their code.
Example:
python
CopyEdit
def logger(func):
print(f"Calling {func.__name__}")
return wrapper
@logger
def greet(name):
print(f"Hello, {name}!")
greet("Anusha")
# Hello, Anusha!
Explanation: Enhances functions with additional logic (like logging) using @decorator syntax.
Definition:
Example:
python
CopyEdit
nums = [1, 2, 3, 4]
print(reduce(lambda x, y: x + y, nums)) # 10
Example:
python
CopyEdit
stack = []
stack.append('A') # Push
stack.append('B')
print(stack.pop()) # Output: B
Explanation: Use .append() to push and .pop() to remove the top element.
Definition: Implementing stack using class for better abstraction and reuse.
Example:
python
CopyEdit
class Stack:
def __init__(self):
self.items = []
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return len(self.items) == 0
s = Stack()
s.push(1)
print(s.pop()) # Output: 1
Explanation: Encapsulates stack operations within a class for clean, structured use.
Example:
python
CopyEdit
def reverse_string(s):
stack = list(s)
result = ''
while stack:
result += stack.pop()
return result
Explanation: Shows real-world stack usage by reversing the order of characters (LIFO principle).
1. Functions (with Parameters & Return Values)
Definition: Blocks of reusable code that can accept inputs (parameters) and optionally return
outputs.
Example:
python
CopyEdit
def greet(name):
2. Variable Scope
Example:
python
CopyEdit
x = 10 # Global
def show():
x = 5 # Local
print(x) # Output: 5
3. Data Types
• String (str):
python
CopyEdit
name = "Python"
CopyEdit
age = 20
pi = 3.14
is_valid = True
• List:
python
CopyEdit
colors.append('blue')
• Tuple:
python
CopyEdit
point = (1, 2)
• Dictionary:
python
CopyEdit
print(student["name"])
• Set:
python
CopyEdit
s = {1, 2, 2, 3}
Explanation: These are the core building blocks for data representation and manipulation.
4. Operators
• Arithmetic:
python
CopyEdit
print(5 + 3) # Output: 8
• Comparison:
python
CopyEdit
• Logical:
python
CopyEdit
• Bitwise:
python
CopyEdit
5. Control Structures
• If-Else:
python
CopyEdit
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
• While Loop:
python
CopyEdit
i=0
while i < 3:
print(i)
i += 1
• For Loop:
python
CopyEdit
for i in range(3):
print(i)
Explanation: Control the flow of program execution based on conditions and repetition.
6. Error Handling
Example:
python
CopyEdit
try:
print(10 / 0)
except ZeroDivisionError:
7. Recursion
Example:
python
CopyEdit
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
8. Decorators
python
CopyEdit
def decorator(func):
def wrapper():
func()
return wrapper
@decorator
def say_hello():
print("Hello!")
say_hello()
9. Lambda Functions
Example:
python
CopyEdit
square = lambda x: x * x
print(square(4)) # Output: 16
• Map:
python
CopyEdit
python
CopyEdit
• Reduce:
python
CopyEdit
python
CopyEdit
class Dog:
self.name = name
def speak(self):
d = Dog("Buddy")
print(d.speak())
• Inheritance:
python
CopyEdit
class Puppy(Dog):
def speak(self):
• Operator Overloading:
python
CopyEdit
class Point:
self.x, self.y = x, y
p1 = Point(1, 2)
p2 = Point(3, 4)
Explanation: OOP promotes encapsulation, code reuse, and logical structuring for large projects.
• Importing Modules:
python
CopyEdit
import math
• Using pip:
bash
CopyEdit
• Example:
python
CopyEdit
import requests
r = requests.get("https://api.github.com")
print(r.status_code)
Explanation: Modules and pip extend Python's capabilities with built-in and third-party packages.
13. Real-World Project: Blackjack Game
Project Structure:
Example Snippet:
python
CopyEdit
class Card:
self.suit = suit
self.rank = rank
def __str__(self):