Python Programming
From Basic to Advanced
A Complete Guide with Theory & Examples
Prepared by Claude | Anthropic | 2025
Table of Contents
Chapter 1: Introduction to Python
Chapter 2: Variables, Data Types & Operators
Chapter 3: Control Flow - Conditions & Loops
Chapter 4: Functions
Chapter 5: Data Structures
Chapter 6: Strings In Depth
Chapter 7: File Handling
Chapter 8: Object-Oriented Programming (OOP)
Chapter 9: Modules & Packages
Chapter 10: Exception Handling
Chapter 11: Advanced Python Concepts
Chapter 12: Python Standard Library
Chapter 13: Working with Databases
Chapter 14: Web Development Basics
Chapter 15: Projects & Best Practices
Chapter 1: Introduction to Python
1.1 What is Python?
Python is a high-level, interpreted, and general-purpose programming language.
Created by Guido van Rossum and first released in 1991, Python has grown to become
one of the most popular programming languages in the world. It emphasizes code
readability and simplicity, using indentation to define code blocks instead of curly
braces.
Python supports multiple programming paradigms including procedural, object-oriented,
and functional programming. It has a vast standard library and a rich ecosystem of third-
party packages.
1.2 Why Learn Python?
• Simple and readable syntax — great for beginners
• Versatile: used in web development, data science, AI/ML, automation, and more
• Large community and extensive library support
• In-demand in the job market
• Cross-platform: runs on Windows, macOS, and Linux
1.3 Installing Python
To install Python, go to [Link] and download the latest version. During
installation on Windows, make sure to check 'Add Python to PATH'. You can verify your
installation by opening a terminal and typing:
python --version
# Output: Python 3.x.x
1.4 Your First Python Program
The traditional first program in any language is to print 'Hello, World!' to the screen. In
Python, this is incredibly simple:
# This is a comment
print("Hello, World!")
# Output:
# Hello, World!
Note: Python uses the print() function to display output. Comments start with the #
symbol and are ignored by the interpreter.
1.5 Python IDEs and Editors
You can write Python code in various environments: IDLE (comes with Python), VS
Code, PyCharm, Jupyter Notebook (great for data science), or even a simple text editor.
For beginners, VS Code with the Python extension is recommended.
Chapter 2: Variables, Data Types & Operators
2.1 Variables
A variable is a named container that stores data in memory. In Python, you do not need
to declare a variable's type — it is inferred automatically. Variable names are case-
sensitive and must start with a letter or underscore.
name = 'Alice'
age = 25
height = 5.7
is_student = True
print(name) # Alice
print(age) # 25
print(height) # 5.7
2.2 Data Types
Python has several built-in data types:
• int — Integer numbers: 10, -5, 1000
• float — Decimal numbers: 3.14, -0.5
• str — Text strings: 'Hello', "World"
• bool — Boolean values: True or False
• NoneType — Represents absence of value: None
• list — Ordered, mutable collection: [1, 2, 3]
• tuple — Ordered, immutable collection: (1, 2, 3)
• dict — Key-value pairs: {'key': 'value'}
• set — Unordered unique values: {1, 2, 3}
# Checking data type with type()
x = 42
print(type(x)) # <class 'int'>
y = 3.14
print(type(y)) # <class 'float'>
s = 'Python'
print(type(s)) # <class 'str'>
b = True
print(type(b)) # <class 'bool'>
2.3 Type Conversion
You can convert between types using built-in functions:
# Type conversion examples
x = int('42') # string to int: 42
y = float('3.14') # string to float: 3.14
z = str(100) # int to string: '100'
b = bool(0) # int to bool: False
b2 = bool(1) # int to bool: True
2.4 Operators
Arithmetic Operators
a, b = 10, 3
print(a + b) # Addition: 13
print(a - b) # Subtraction: 7
print(a * b) # Multiplication: 30
print(a / b) # Division: 3.333...
print(a // b) # Floor Division: 3
print(a % b) # Modulus: 1
print(a ** b) # Exponentiation: 1000
Comparison Operators
x, y = 5, 10
print(x == y) # Equal: False
print(x != y) # Not Equal: True
print(x < y) # Less than: True
print(x > y) # Greater than: False
print(x <= y) # Less than or equal: True
print(x >= y) # Greater than or equal: False
Logical Operators
a, b = True, False
print(a and b) # False — both must be True
print(a or b) # True — at least one True
print(not a) # False — inverts value
Assignment Operators
x = 10
x += 5 # x = x + 5 -> 15
x -= 3 # x = x - 3 -> 12
x *= 2 # x = x * 2 -> 24
x //= 4 # x = x // 4 -> 6
print(x) # 6
Chapter 3: Control Flow — Conditions & Loops
3.1 if / elif / else Statements
Conditional statements allow your program to make decisions based on whether
conditions are True or False.
age = 18
if age < 13:
print('Child')
elif age < 18:
print('Teenager')
elif age == 18:
print('Just became an adult!')
else:
print('Adult')
# Output: Just became an adult!
3.2 Nested Conditions
username = 'admin'
password = '1234'
if username == 'admin':
if password == '1234':
print('Login successful')
else:
print('Wrong password')
else:
print('Unknown user')
3.3 The for Loop
The for loop iterates over a sequence (list, tuple, string, range, etc.).
# Iterating over a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# Using range()
for i in range(1, 6): # 1 to 5
print(i)
# range(start, stop, step)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)
3.4 The while Loop
The while loop keeps running as long as a condition is True.
count = 1
while count <= 5:
print(f'Count: {count}')
count += 1
# Count: 1
# Count: 2 ... Count: 5
3.5 break, continue, and pass
# break — exits the loop entirely
for i in range(10):
if i == 5:
break
print(i) # prints 0 to 4
# continue — skips the rest of the current iteration
for i in range(10):
if i % 2 == 0:
continue
print(i) # prints odd numbers: 1, 3, 5, 7, 9
# pass — does nothing; used as a placeholder
for i in range(3):
pass # loop runs but nothing happens
Note: Always make sure while loops have a way to terminate to avoid infinite loops.
Chapter 4: Functions
4.1 What is a Function?
A function is a reusable block of code that performs a specific task. Functions help you
avoid repetition and organize your code into logical, manageable pieces. In Python,
functions are defined using the def keyword.
4.2 Defining and Calling Functions
def greet():
print('Hello, World!')
greet() # Call the function -> Hello, World!
4.3 Parameters and Arguments
# Function with parameters
def greet(name):
print(f'Hello, {name}!')
greet('Alice') # Hello, Alice!
greet('Bob') # Hello, Bob!
# Default parameter value
def power(base, exponent=2):
return base ** exponent
print(power(3)) # 9 (uses default exponent=2)
print(power(3, 3)) # 27
4.4 Return Values
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
# Returning multiple values
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 8, 2])
print(low, high) # 1 8
4.5 *args and **kwargs
# *args — accepts variable number of positional arguments
def total(*args):
return sum(args)
print(total(1, 2, 3, 4)) # 10
# **kwargs — accepts variable number of keyword arguments
def show_info(**kwargs):
for key, value in [Link]():
print(f'{key}: {value}')
show_info(name='Alice', age=25, city='NYC')
4.6 Lambda Functions
Lambda functions are small, anonymous (nameless) functions written in a single line.
They are often used for quick, short operations.
# Regular function
def square(x):
return x ** 2
# Equivalent lambda function
square = lambda x: x ** 2
print(square(5)) # 25
# Lambda with multiple params
add = lambda a, b: a + b
print(add(3, 4)) # 7
# Common use: with sorted()
people = [('Alice', 30), ('Bob', 25), ('Charlie', 35)]
[Link](key=lambda p: p[1]) # sort by age
print(people)
4.7 Scope — Local vs Global Variables
x = 10 # Global variable
def show():
x = 20 # Local variable (doesn't change global x)
print(x) # 20
show()
print(x) # 10 — global x unchanged
# Use 'global' keyword to modify global variable inside a function
def change():
global x
x = 99
change()
print(x) # 99
Chapter 5: Data Structures
5.1 Lists
Lists are ordered, mutable (changeable) collections that can hold items of any data
type.
# Creating a list
fruits = ['apple', 'banana', 'cherry']
# Accessing elements (zero-indexed)
print(fruits[0]) # apple
print(fruits[-1]) # cherry (last item)
# Slicing
print(fruits[0:2]) # ['apple', 'banana']
# List methods
[Link]('mango') # add to end
[Link](1, 'blueberry') # insert at index
[Link]('banana') # remove by value
popped = [Link]() # remove & return last
[Link]() # sort in place
[Link]() # reverse in place
print(len(fruits)) # length of list
5.2 List Comprehensions
List comprehensions provide a concise way to create lists based on existing iterables.
# Traditional way
squares = []
for i in range(1, 6):
[Link](i ** 2)
# List comprehension — much cleaner!
squares = [i ** 2 for i in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# With condition
evens = [i for i in range(20) if i % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
5.3 Tuples
Tuples are like lists but they are immutable — once created, their values cannot be
changed. They are faster than lists and useful for protecting data.
coordinates = (10.5, 20.3)
rgb = (255, 128, 0)
print(coordinates[0]) # 10.5
# Tuple unpacking
x, y = coordinates
print(x, y) # 10.5 20.3
# One-element tuple needs a trailing comma
single = (42,)
print(type(single)) # <class 'tuple'>
5.4 Dictionaries
Dictionaries store data as key-value pairs. They are unordered (in Python < 3.7) but
maintain insertion order in Python 3.7+. Keys must be unique and immutable.
student = {
'name': 'Alice',
'age': 20,
'grade': 'A'
}
# Access values
print(student['name']) # Alice
print([Link]('age')) # 20
print([Link]('email', 'N/A')) # N/A (default)
# Modify / Add
student['age'] = 21
student['email'] = 'alice@[Link]'
# Delete
del student['grade']
# Iterate
for key, value in [Link]():
print(f'{key}: {value}')
# Useful methods
print([Link]())
print([Link]())
5.5 Sets
Sets are unordered collections of unique elements. They are useful for removing
duplicates and performing set operations like union and intersection.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # Union: {1, 2, 3, 4, 5, 6}
print(a & b) # Intersection: {3, 4}
print(a - b) # Difference: {1, 2}
print(a ^ b) # Symmetric difference: {1, 2, 5, 6}
# Remove duplicates from list using set
nums = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(nums))
print(unique) # [1, 2, 3, 4]
Chapter 6: Strings In Depth
6.1 String Basics
Strings in Python are sequences of characters enclosed in single quotes, double
quotes, or triple quotes. Strings are immutable.
s1 = 'Hello'
s2 = "World"
s3 = '''This is a
multi-line string'''
# Concatenation
full = s1 + ', ' + s2 + '!'
print(full) # Hello, World!
# Repetition
print('Ha' * 3) # HaHaHa
# Length
print(len(full)) # 13
6.2 String Methods
text = ' Hello, Python World! '
print([Link]()) # removes leading/trailing spaces
print([Link]()) # to lowercase
print([Link]()) # to uppercase
print([Link]('Python', 'Beautiful')) # replace substring
print([Link]('Python')) # returns index or -1
print([Link](',')) # split into list
print([Link](' Hello')) # True
print([Link]('! ')) # True
print('Python'.center(20, '-')) # ---Python----
6.3 f-Strings (Formatted String Literals)
f-strings are the modern, preferred way to format strings in Python 3.6+. They allow you
to embed expressions inside string literals.
name = 'Alice'
age = 25
gpa = 3.875
# f-string
print(f'Name: {name}, Age: {age}')
print(f'GPA: {gpa:.2f}') # format to 2 decimal places
print(f'2 + 2 = {2 + 2}') # expressions work too
print(f'{[Link]()} is {age} years old')
6.4 String Slicing
s = 'Python Programming'
print(s[0:6]) # 'Python'
print(s[7:]) # 'Programming'
print(s[-11:]) # 'Programming'
print(s[::2]) # every other char: 'Pto rgamn'
print(s[::-1]) # reversed: 'gnimmargorP nohtyP'
Chapter 7: File Handling
7.1 Opening and Reading Files
Python can read from and write to files using the built-in open() function. Always use the
'with' statement to ensure the file is properly closed after use.
# Reading an entire file
with open('[Link]', 'r') as f:
content = [Link]()
print(content)
# Reading line by line
with open('[Link]', 'r') as f:
for line in f:
print([Link]())
# Reading all lines into a list
with open('[Link]', 'r') as f:
lines = [Link]()
7.2 Writing to Files
# Writing (overwrites existing content)
with open('[Link]', 'w') as f:
[Link]('Hello, File!\n')
[Link]('Second line\n')
# Appending to file
with open('[Link]', 'a') as f:
[Link]('This is appended\n')
7.3 Working with CSV Files
import csv
# Writing CSV
with open('[Link]', 'w', newline='') as f:
writer = [Link](f)
[Link](['Name', 'Age', 'Grade'])
[Link](['Alice', 20, 'A'])
[Link](['Bob', 22, 'B'])
# Reading CSV
with open('[Link]', 'r') as f:
reader = [Link](f)
for row in reader:
print(row['Name'], row['Grade'])
7.4 Working with JSON Files
import json
data = {'name': 'Alice', 'age': 25, 'skills': ['Python', 'SQL']}
# Write JSON
with open('[Link]', 'w') as f:
[Link](data, f, indent=4)
# Read JSON
with open('[Link]', 'r') as f:
loaded = [Link](f)
print(loaded['name']) # Alice
Chapter 8: Object-Oriented Programming (OOP)
8.1 What is OOP?
Object-Oriented Programming is a paradigm that organizes code around objects rather
than functions. An object is an instance of a class. Classes act as blueprints that define
the properties (attributes) and behaviors (methods) of objects. OOP makes code more
modular, reusable, and easier to maintain.
8.2 Classes and Objects
class Dog:
# Class attribute (shared by all instances)
species = 'Canis familiaris'
# Constructor: runs when object is created
def __init__(self, name, age):
[Link] = name # instance attribute
[Link] = age
# Method
def bark(self):
print(f'{[Link]} says: Woof!')
def __str__(self):
return f'Dog({[Link]}, {[Link]} years)'
# Create objects (instances)
dog1 = Dog('Rex', 3)
dog2 = Dog('Buddy', 5)
[Link]() # Rex says: Woof!
print(dog1) # Dog(Rex, 3 years)
print([Link]) # Canis familiaris
8.3 Inheritance
Inheritance allows a class (child) to inherit attributes and methods from another class
(parent). This promotes code reuse.
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
raise NotImplementedError('Subclass must implement this')
class Dog(Animal):
def speak(self):
return f'{[Link]} says Woof!'
class Cat(Animal):
def speak(self):
return f'{[Link]} says Meow!'
animals = [Dog('Rex'), Cat('Whiskers')]
for animal in animals:
print([Link]())
8.4 Encapsulation
Encapsulation restricts direct access to an object's data and methods. In Python, a
single underscore (_name) signals 'protected' and double underscore (__name) makes
it 'private'.
class BankAccount:
def __init__(self, owner, balance):
[Link] = owner
self.__balance = balance # private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def get_balance(self):
return self.__balance
acc = BankAccount('Alice', 1000)
[Link](500)
print(acc.get_balance()) # 1500
# print(acc.__balance) # AttributeError!
8.5 Polymorphism
Polymorphism means 'many forms'. It allows different classes to implement the same
interface (method names) in different ways.
class Circle:
def __init__(self, radius):
[Link] = radius
def area(self):
return 3.14159 * [Link] ** 2
class Rectangle:
def __init__(self, w, h):
self.w, self.h = w, h
def area(self):
return self.w * self.h
shapes = [Circle(5), Rectangle(4, 6)]
for shape in shapes:
print(f'Area: {[Link]():.2f}')
Chapter 9: Modules & Packages
9.1 What are Modules?
A module is a Python file (.py) containing functions, classes, or variables that can be
imported and used in other programs. Python comes with a large standard library of
modules, and you can also install third-party modules using pip.
# Importing a module
import math
print([Link]) # 3.141592653589793
print([Link](16)) # 4.0
print([Link](4.2)) # 5
print([Link](4.9)) # 4
print([Link](2, 10)) # 1024.0
9.2 Different Import Styles
# Import specific items
from math import sqrt, pi
print(sqrt(25)) # 5.0
# Import with alias
import numpy as np # popular convention
import pandas as pd
# Import everything (not recommended for large modules)
from math import *
print(sin(pi / 2)) # 1.0
9.3 Creating Your Own Module
# File: [Link]
def greet(name):
return f'Hello, {name}!'
def square(n):
return n ** 2
PI = 3.14159
# ===========================
# File: [Link]
import myutils
print([Link]('Alice')) # Hello, Alice!
print([Link](5)) # 25
9.4 Installing Third-Party Packages
# Install packages using pip (in terminal)
pip install requests # HTTP library
pip install numpy # numerical computing
pip install pandas # data analysis
pip install matplotlib # data visualization
# Example: using requests
import requests
response = [Link]('[Link]
print(response.status_code) # 200
print([Link]())
Chapter 10: Exception Handling
10.1 What are Exceptions?
An exception is an error that occurs during program execution. Without handling,
exceptions crash your program. Python provides a try / except structure to catch and
handle exceptions gracefully.
# Without exception handling — crashes
# print(10 / 0) # ZeroDivisionError
# With exception handling
try:
result = 10 / 0
except ZeroDivisionError:
print('Cannot divide by zero!')
# Multiple except blocks
try:
num = int(input('Enter a number: '))
result = 100 / num
print(f'Result: {result}')
except ValueError:
print('Please enter a valid integer')
except ZeroDivisionError:
print('Cannot divide by zero')
except Exception as e:
print(f'Unexpected error: {e}')
10.2 else and finally
try:
f = open('[Link]', 'r')
content = [Link]()
except FileNotFoundError:
print('File not found!')
else:
# Runs only if no exception occurred
print('File read successfully')
print(content)
finally:
# Always runs, whether exception or not
print('Done processing file')
10.3 Raising Exceptions
def set_age(age):
if age < 0 or age > 150:
raise ValueError(f'Invalid age: {age}')
return age
try:
set_age(-5)
except ValueError as e:
print(e) # Invalid age: -5
10.4 Custom Exceptions
class InsufficientFundsError(Exception):
def __init__(self, amount, balance):
[Link] = amount
[Link] = balance
super().__init__(f'Cannot withdraw {amount}, balance is {balance}')
class BankAccount:
def __init__(self, balance):
[Link] = balance
def withdraw(self, amount):
if amount > [Link]:
raise InsufficientFundsError(amount, [Link])
[Link] -= amount
acc = BankAccount(100)
try:
[Link](200)
except InsufficientFundsError as e:
print(e)
Chapter 11: Advanced Python Concepts
11.1 Decorators
Decorators are functions that modify the behavior of another function. They are defined
with the @ symbol and are commonly used for logging, timing, authentication, and
caching.
def timer(func):
import time
def wrapper(*args, **kwargs):
start = [Link]()
result = func(*args, **kwargs)
end = [Link]()
print(f'{func.__name__} took {end - start:.4f}s')
return result
return wrapper
@timer
def slow_add(a, b):
import time; [Link](0.1)
return a + b
print(slow_add(3, 4)) # 7 (and prints timing)
11.2 Generators
Generators are functions that produce a sequence of values lazily (one at a time), using
the yield keyword. They are memory-efficient for large data sequences.
# Regular function returns all at once
def squares_list(n):
return [i ** 2 for i in range(n)]
# Generator yields one at a time
def squares_gen(n):
for i in range(n):
yield i ** 2
gen = squares_gen(5)
print(next(gen)) # 0
print(next(gen)) # 1
print(next(gen)) # 4
# Or use in a for loop
for sq in squares_gen(5):
print(sq)
11.3 Context Managers
# Custom context manager using class
class ManagedFile:
def __init__(self, filename, mode):
[Link] = filename
[Link] = mode
def __enter__(self):
[Link] = open([Link], [Link])
return [Link]
def __exit__(self, exc_type, exc_val, exc_tb):
[Link]()
return False
with ManagedFile('[Link]', 'w') as f:
[Link]('Hello!')
11.4 Iterators
class CountUp:
def __init__(self, start, end):
[Link] = start
[Link] = end
def __iter__(self):
return self
def __next__(self):
if [Link] > [Link]:
raise StopIteration
value = [Link]
[Link] += 1
return value
for num in CountUp(1, 5):
print(num) # 1, 2, 3, 4, 5
11.5 Comprehensions — Dict and Set
# Dictionary comprehension
words = ['hello', 'world', 'python']
word_lengths = {word: len(word) for word in words}
print(word_lengths) # {'hello': 5, 'world': 5, 'python': 6}
# Set comprehension
nums = [1, 1, 2, 2, 3, 4, 4]
unique_squares = {x ** 2 for x in nums}
print(unique_squares) # {1, 4, 9, 16}
# Generator expression (no brackets)
total = sum(x ** 2 for x in range(10))
print(total) # 285
11.6 The map(), filter(), zip() Functions
numbers = [1, 2, 3, 4, 5]
# map — apply function to each element
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # [2, 4, 6, 8, 10]
# filter — keep elements where function is True
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4]
# zip — combine multiple iterables
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]
combined = list(zip(names, scores))
print(combined) # [('Alice', 85), ('Bob', 92), ('Charlie', 78)]
Chapter 12: Python Standard Library
12.1 datetime Module
from datetime import datetime, date, timedelta
now = [Link]()
print(now) # current datetime
print([Link]('%Y-%m-%d %H:%M')) # formatted
today = [Link]()
print(today) # e.g. 2025-01-15
future = today + timedelta(days=30)
print(future)
12.2 os and sys Modules
import os
print([Link]()) # current directory
[Link]('new_dir', exist_ok=True) # create dir
files = [Link]('.') # list files in dir
print([Link]('folder', '[Link]')) # path joining
print([Link]('[Link]')) # check if exists
import sys
print([Link]) # Python version
print([Link]) # command line arguments
12.3 random Module
import random
print([Link]()) # float 0.0 to 1.0
print([Link](1, 100)) # int between 1 and 100
print([Link](['a', 'b', 'c'])) # random item
items = [1, 2, 3, 4, 5]
[Link](items) # shuffle in place
print(items)
print([Link](items, 3)) # random 3 items (no repeat)
12.4 collections Module
from collections import Counter, defaultdict, deque
# Counter — count occurrences
words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
count = Counter(words)
print(count) # Counter({'apple': 3, ...})
print(count.most_common(2)) # top 2
# defaultdict — dict with default value for missing keys
dd = defaultdict(list)
dd['fruits'].append('apple')
dd['fruits'].append('banana')
print(dd) # defaultdict(<class 'list'>, {'fruits': ['apple', 'banana']})
# deque — fast append/pop from both ends
d = deque([1, 2, 3])
[Link](0)
[Link](4)
[Link]() # removes 0
print(d) # deque([1, 2, 3, 4])
Chapter 13: Working with Databases
13.1 SQLite with Python
Python's built-in sqlite3 module lets you work with SQLite databases without any
installation. SQLite is a lightweight, file-based relational database perfect for small to
medium applications.
import sqlite3
# Connect (creates file if not exists)
conn = [Link]('[Link]')
cursor = [Link]()
# Create table
[Link]('''
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
grade TEXT
)
''')
# Insert data
[Link]('INSERT INTO students (name, age, grade) VALUES (?, ?, ?)',
('Alice', 20, 'A'))
[Link]('INSERT INTO students (name, age, grade) VALUES (?, ?, ?)',
('Bob', 22, 'B'))
[Link]()
# Query data
[Link]('SELECT * FROM students')
rows = [Link]()
for row in rows:
print(row)
[Link]()
Chapter 14: Web Development Basics
14.1 Introduction to Flask
Flask is a lightweight web framework for Python. It allows you to build web applications
quickly with minimal setup.
# Install: pip install flask
from flask import Flask, request, jsonify
app = Flask(__name__)
@[Link]('/')
def home():
return '<h1>Hello, World!</h1>'
@[Link]('/user/<name>')
def user(name):
return f'<h2>Hello, {name}!</h2>'
@[Link]('/api/data', methods=['GET'])
def api_data():
data = {'message': 'Hello', 'status': 200}
return jsonify(data)
if __name__ == '__main__':
[Link](debug=True)
14.2 Making HTTP Requests
# Install: pip install requests
import requests
# GET request
response = [Link]('[Link]
data = [Link]()
print(data['title'])
# POST request
payload = {'title': 'New Todo', 'completed': False, 'userId': 1}
response = [Link](
'[Link]
json=payload
)
print(response.status_code, [Link]())
Chapter 15: Projects & Best Practices
15.1 Project 1 — Number Guessing Game
import random
def guessing_game():
secret = [Link](1, 100)
attempts = 0
print('Guess the number between 1 and 100!')
while True:
try:
guess = int(input('Your guess: '))
except ValueError:
print('Please enter a valid number')
continue
attempts += 1
if guess < secret:
print('Too low!')
elif guess > secret:
print('Too high!')
else:
print(f'Correct! You won in {attempts} attempts!')
break
guessing_game()
15.2 Project 2 — Simple Contact Book
class ContactBook:
def __init__(self):
[Link] = {}
def add(self, name, phone):
[Link][name] = phone
print(f'Added {name}')
def find(self, name):
phone = [Link](name)
if phone:
print(f'{name}: {phone}')
else:
print(f'{name} not found')
def delete(self, name):
if name in [Link]:
del [Link][name]
print(f'Deleted {name}')
def list_all(self):
for name, phone in [Link]():
print(f'{name}: {phone}')
book = ContactBook()
[Link]('Alice', '555-1234')
[Link]('Bob', '555-5678')
[Link]('Alice')
book.list_all()
15.3 Python Best Practices
Following best practices makes your code clean, readable, and maintainable:
• Follow PEP 8 — Python's official style guide (use 4 spaces for indentation,
snake_case for variable names, etc.)
• Write meaningful variable and function names that describe their purpose
• Keep functions small and focused — each function should do one thing
• Use docstrings to document your functions and classes
• Write comments where code is complex or non-obvious
• Handle exceptions properly — never use bare 'except:' clauses
• Use list/dict comprehensions for concise, readable code
• Use virtual environments (venv) for each project to isolate dependencies
• Write unit tests for your code using Python's unittest or pytest
• Use version control (Git) to track changes in your code
15.4 Writing Docstrings
def calculate_bmi(weight_kg, height_m):
'''
Calculate Body Mass Index (BMI).
Args:
weight_kg (float): Weight in kilograms.
height_m (float): Height in meters.
Returns:
float: The BMI value.
Example:
>>> calculate_bmi(70, 1.75)
22.857142857142858
'''
return weight_kg / (height_m ** 2)
# Access docstring
help(calculate_bmi)
15.5 Virtual Environments
# Create a virtual environment
python -m venv myenv
# Activate (Windows)
myenv\Scripts\activate
# Activate (macOS/Linux)
source myenv/bin/activate
# Install packages in the environment
pip install flask requests numpy
# Save dependencies to file
pip freeze > [Link]
# Install from [Link]
pip install -r [Link]
# Deactivate
deactivate
Conclusion
Congratulations on completing this Python programming book! You have covered a
tremendous amount of ground — from writing your very first print() statement all the way
to building object-oriented applications, handling files and databases, and creating web
APIs.
Python is a language where practice is everything. The concepts you have learned here
will become second nature the more you use them. Here is what you should do next:
• Practice daily — write small programs to reinforce each concept
• Work on real projects — personal projects are the best teachers
• Explore specialized libraries like NumPy, Pandas, Matplotlib for data science
• Learn Django or FastAPI for web development
• Contribute to open-source projects on GitHub
• Study algorithms and data structures to become a stronger programmer
• Take on coding challenges on LeetCode, HackerRank, or Codewars
Remember that every expert was once a beginner. Be patient with yourself, stay
curious, and keep coding. Python is not just a programming language — it is a
superpower that will open doors to countless opportunities in technology, science,
finance, and beyond.
Happy Coding!