Comprehensive Python Programming Guide: Data Types, Control Flow, Functions, OOP, and Advanced Features
This guide provides a thorough overview of Python programming, covering basic data types, control flow statements, function definitions, modules and packages, exception handling, file I/O, object‑oriented concepts, iterators, generators, context managers, decorators, functional programming, asynchronous code, metaclasses, standard and third‑party libraries, type annotations, design patterns, and practical tips such as enums and dataclasses.
1. Basic Data Types – Demonstrates integers, floats, complex numbers, strings (single, double, triple quotes), lists, tuples, sets, and dictionaries with example code.
int a = 10
float b = 3.14
complex c = 2 + 3j
s1 = 'Hello, world!'
s2 = "Python 3"
s3 = """This is a
multi-line string."""
my_list = [1, 2, 3, 'four', 5.0]
my_tuple = (1, 2, 3, 'four', 5.0)
my_set = {1, 2, 3, 4, 5}
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}2. Control Flow Statements – Shows conditional statements (if/elif/else) and loops (for, while) with break, continue, and pass examples.
x = 10
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
for i in range(5):
print(i)
i = 0
while i < 5:
print(i)
i += 1
for i in range(10):
if i == 5:
break
print(i)3. Functions – Defines functions with positional, keyword, default, *args, and **kwargs parameters and shows calling them.
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
def add(a, b=10):
return a + b
print(add(5))
def multiply(*args):
result = 1
for num in args:
result *= num
return result
print(multiply(1, 2, 3))
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=30)4. Modules and Packages – Illustrates importing built‑in modules and creating a simple package with __init__.py.
import math
from datetime import datetime
print(math.sqrt(16))
print(datetime.now())
# mypackage/__init__.py
from . import module1
from . import module2
# mypackage/module1.py
def func1():
print("Function from module1")
# mypackage/module2.py
def func2():
print("Function from module2")
import mypackage.module1 as m1
import mypackage.module2 as m2
m1.func1()
m2.func2()5. Exception Handling – Shows try/except/else/finally blocks.
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("No exceptions were raised")
finally:
print("This will always execute")6. File Operations – Demonstrates writing to and reading from a file using the with statement.
with open('example.txt', 'w') as file:
file.write("Hello, world!")
with open('example.txt', 'r') as file:
content = file.read()
print(content)7. Classes and Objects – Covers class definition, inheritance, and polymorphism.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
p = Person("Alice", 30)
p.greet()
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
def study(self):
print(f"{self.name} is studying.")
s = Student("Bob", 20, 101)
s.greet()
s.study()
class Teacher(Person):
def __init__(self, name, age, subject):
super().__init__(name, age)
self.subject = subject
def greet(self):
print(f"Hello, I am {self.name}, and I teach {self.subject}.")
t = Teacher("Charlie", 40, "Math")
t.greet()8. Iterators and Generators – Implements a custom iterator class and a generator function.
class MyIterator:
def __init__(self, max_value):
self.max_value = max_value
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current < self.max_value:
value = self.current
self.current += 1
return value
else:
raise StopIteration
for num in MyIterator(5):
print(num)
def my_generator(max_value):
current = 0
while current < max_value:
yield current
current += 1
for num in my_generator(5):
print(num)9. Context Managers – Shows a class‑based context manager and usage with the with statement.
class ManagedResource:
def __enter__(self):
print("Resource acquired")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Resource released")
def do_something(self):
print("Doing something with the resource")
with ManagedResource() as resource:
resource.do_something()10. Decorators – Simple function decorator that prints messages before and after the wrapped function.
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Something is happening before the function is called.")
result = func(*args, **kwargs)
print("Something is happening after the function is called.")
return result
return wrapper
@my_decorator
def say_hello(name):
print(f"Hello, {name}!")
say_hello("Alice")11. Advanced Features – List, dict, and set comprehensions, generator expressions, lambda functions, map, filter, and reduce.
squares = [x * x for x in range(10)]
print(squares)
squares_dict = {x: x * x for x in range(10)}
print(squares_dict)
squares_set = {x * x for x in range(10)}
print(squares_set)
squares_gen = (x * x for x in range(10))
for square in squares_gen:
print(square)
add = lambda x, y: x + y
print(add(5, 3))
numbers = [1, 2, 3, 4]
squared = map(lambda x: x * x, numbers)
print(list(squared))
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)
print(product)12. Functional Programming – Higher‑order functions and partial application.
def apply(func, value):
return func(value)
result = apply(lambda x: x * x, 5)
print(result)
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
print(square(5))
print(cube(5))13. Asynchronous Programming – Async/await coroutines and asynchronous generators.
import asyncio
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
task1 = asyncio.create_task(say_after(1, 'hello'))
task2 = asyncio.create_task(say_after(2, 'world'))
await task1
await task2
asyncio.run(main())
async def async_range(count):
for i in range(count):
yield i
await asyncio.sleep(0.1)
async def main2():
async for i in async_range(5):
print(i)
asyncio.run(main2())14. Metaclasses – Creating classes with type and custom metaclasses.
MyClass = type('MyClass', (object,), {'x': 5, 'y': 10})
instance = MyClass()
print(instance.x)
print(instance.y)
class MyMeta(type):
def __new__(cls, name, bases, dct):
dct['greet'] = lambda self: f"Hello from {name}"
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=MyMeta):
pass
instance = MyClass()
print(instance.greet())15. Standard Library Modules – Examples using os, sys, datetime, json, re, and random.
import os, sys
print(os.getcwd())
print(sys.platform)
print(sys.argv)
from datetime import datetime, timedelta
now = datetime.now()
print(now)
print(now + timedelta(days=1))
import json
data = {'name': 'Alice', 'age': 30, 'city': 'New York'}
json_str = json.dumps(data)
print(json_str)
print(json.loads(json_str))
import re
text = "The quick brown fox jumps over the lazy dog."
pattern = r'\b\w{5}\b'
print(re.findall(pattern, text))
import random
print(random.randint(1, 100))
print(random.choice(['apple', 'banana', 'cherry']))16. Third‑Party Libraries – Brief usage of requests, pandas, numpy, and matplotlib.
import requests
resp = requests.get('https://api.github.com')
print(resp.status_code)
print(resp.json())
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'City': ['New York', 'Los Angeles', 'Chicago']}
df = pd.DataFrame(data)
print(df)
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(np.mean(arr))
print(np.max(arr))
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y)
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title('Simple Plot')
plt.show()17. Advanced Context Manager Usage – Class‑based and @contextmanager implementations.
from contextlib import contextmanager
class ManagedResource:
def __enter__(self):
print('Resource acquired')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('Resource released')
def do_something(self):
print('Doing something with the resource')
with ManagedResource() as r:
r.do_something()
@contextmanager
def managed_resource():
print('Resource acquired')
try:
yield
finally:
print('Resource released')
with managed_resource():
print('Doing something with the resource')18. Advanced Decorator Techniques – Parameterized decorators and class‑based decorators.
def repeat(num_times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(num_times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}!")
greet('Alice')
class DebugDecorator:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print(f"Calling {self.func.__name__} with args: {args}, kwargs: {kwargs}")
result = self.func(*args, **kwargs)
print(f"{self.func.__name__} returned: {result}")
return result
@DebugDecorator
def add(a, b):
return a + b
add(5, 3)19. Type Annotations – Using typing module for static type hints.
from typing import List, Dict, Tuple, Optional
def greet(name: str) -> str:
return f"Hello, {name}!"
def get_names() -> List[str]:
return ["Alice", "Bob", "Charlie"]
def get_info() -> Dict[str, int]:
return {"Alice": 25, "Bob": 30, "Charlie": 35}
def process_data(data: Tuple[int, str, float]) -> None:
num, name, score = data
print(f"Number: {num}, Name: {name}, Score: {score}")
def find_person(people: List[Dict[str, str]], name: str) -> Optional[Dict[str, str]]:
for person in people:
if person['name'] == name:
return person
return None
print(greet("Alice"))
print(get_names())
print(get_info())
process_data((1, "Alice", 95.5))
print(find_person([{'name': 'Alice', 'age': '25'}, {'name': 'Bob', 'age': '30'}], "Alice"))20. Design Patterns – Singleton and Factory pattern implementations.
class Singleton:
_instance = None
@staticmethod
def get_instance():
if Singleton._instance is None:
Singleton._instance = Singleton()
return Singleton._instance
def __init__(self):
if Singleton._instance is not None:
raise Exception("This class is a singleton!")
else:
Singleton._instance = self
singleton1 = Singleton.get_instance()
singleton2 = Singleton.get_instance()
print(singleton1 is singleton2)
from abc import ABC, abstractmethod
class Product(ABC):
@abstractmethod
def use(self):
pass
class ConcreteProductA(Product):
def use(self):
print("Using ConcreteProductA")
class ConcreteProductB(Product):
def use(self):
print("Using ConcreteProductB")
class Factory:
@staticmethod
def create_product(product_type: str) -> Product:
if product_type == "A":
return ConcreteProductA()
elif product_type == "B":
return ConcreteProductB()
else:
raise ValueError("Invalid product type")
product_a = Factory.create_product("A")
product_b = Factory.create_product("B")
product_a.use()
product_b.use()21. Practical Tips – Enum definitions and dataclasses for concise data structures.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.RED)
print(Color.RED.name)
print(Color.RED.value)
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
city: str
person = Person(name="Alice", age=30, city="New York")
print(person)Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.