Python Programming

Complete Guide from Basics to Advanced Concepts

Introduction to Python

Python is a high-level, interpreted programming language known for its simplicity and readability. Created by Guido van Rossum in 1991.

Why Python?

  • Easy to Learn: Simple syntax similar to English
  • Versatile: Web dev, AI/ML, Data Science, Automation
  • Large Community: Extensive libraries and frameworks
  • Cross-Platform: Works on Windows, Mac, Linux
Python
# Your first Python program
print("Hello, World!")

# Taking input from user
name = input("Enter your name: ")
print(f"Welcome, {name}!")

Variables & Data Types

Python is dynamically typed - you don't need to declare variable types explicitly.

Data TypeExampleDescription
intx = 10Integer numbers
floaty = 3.14Decimal numbers
strname = "John"Text strings
boolis_valid = TrueBoolean (True/False)
list[1, 2, 3]Ordered, mutable collection
tuple(1, 2, 3)Ordered, immutable collection
dict{"key": "value"}Key-value pairs
set{1, 2, 3}Unordered unique elements
Python
# Variable declarations
age = 25                    # int
salary = 50000.50           # float
name = "Alice"              # str
is_employed = True          # bool

# Type checking
print(type(age))            # 

# Type conversion
num_str = "100"
num_int = int(num_str)      # Convert to integer

# Multiple assignment
a, b, c = 1, 2, 3
x = y = z = 0               # All equal to 0

Operators

Python
# Arithmetic Operators
a, b = 10, 3
print(a + b)    # 13 - Addition
print(a - b)    # 7  - Subtraction
print(a * b)    # 30 - Multiplication
print(a / b)    # 3.33 - Division (float)
print(a // b)   # 3  - Floor division
print(a % b)    # 1  - Modulus (remainder)
print(a ** b)   # 1000 - Exponentiation

# Comparison Operators
print(a == b)   # False - Equal
print(a != b)   # True  - Not equal
print(a > b)    # True  - Greater than
print(a >= b)   # True  - Greater or equal
print(a < b)    # False - Less than

# Logical Operators
x, y = True, False
print(x and y)  # False
print(x or y)   # True
print(not x)    # False

# Identity Operators
print(a is b)       # False - Same object
print(a is not b)   # True

# Membership Operators
lst = [1, 2, 3]
print(2 in lst)     # True
print(5 not in lst) # True

Control Flow

Conditional Statements

Python
# if-elif-else
age = 18

if age < 13:
    print("Child")
elif age < 20:
    print("Teenager")
else:
    print("Adult")

# Ternary operator
status = "Adult" if age >= 18 else "Minor"

# Match statement (Python 3.10+)
command = "start"
match command:
    case "start":
        print("Starting...")
    case "stop":
        print("Stopping...")
    case _:
        print("Unknown command")

Loops

Python
# For loop
for i in range(5):          # 0 to 4
    print(i)

for i in range(1, 10, 2):   # 1, 3, 5, 7, 9
    print(i)

# Iterate over list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# With index
for idx, fruit in enumerate(fruits):
    print(f"{idx}: {fruit}")

# While loop
count = 0
while count < 5:
    print(count)
    count += 1

# Loop control
for i in range(10):
    if i == 3:
        continue    # Skip 3
    if i == 7:
        break       # Stop at 7
    print(i)

Functions

Python
# Basic function
def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))

# Default parameters
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

# Keyword arguments
print(greet(name="Bob", greeting="Hi"))

# *args - Variable positional arguments
def add_all(*numbers):
    return sum(numbers)

print(add_all(1, 2, 3, 4))  # 10

# **kwargs - Variable keyword arguments
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25, city="NYC")

# Lambda functions (anonymous)
square = lambda x: x ** 2
print(square(5))  # 25

# Higher-order functions
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
evens = list(filter(lambda x: x % 2 == 0, numbers))

Data Structures

Lists

Python
# List - mutable, ordered
fruits = ["apple", "banana", "cherry"]

# Access elements
print(fruits[0])        # apple
print(fruits[-1])       # cherry (last element)
print(fruits[1:3])      # ['banana', 'cherry']

# Modify
fruits.append("orange")         # Add to end
fruits.insert(1, "mango")       # Insert at index
fruits.remove("banana")         # Remove by value
popped = fruits.pop()           # Remove and return last
fruits.extend(["grape", "kiwi"]) # Add multiple

# List comprehension
squares = [x**2 for x in range(1, 6)]  # [1, 4, 9, 16, 25]
evens = [x for x in range(10) if x % 2 == 0]

# Useful methods
fruits.sort()           # Sort in place
fruits.reverse()        # Reverse in place
print(len(fruits))      # Length
print(fruits.count("apple"))  # Count occurrences

Dictionaries

Python
# Dictionary - key-value pairs
person = {
    "name": "Alice",
    "age": 25,
    "city": "NYC"
}

# Access
print(person["name"])           # Alice
print(person.get("salary", 0))  # 0 (default if not found)

# Modify
person["age"] = 26              # Update
person["job"] = "Developer"     # Add new key
del person["city"]              # Delete key

# Iterate
for key in person:
    print(key, person[key])

for key, value in person.items():
    print(f"{key}: {value}")

# Dictionary comprehension
squares_dict = {x: x**2 for x in range(1, 6)}
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Object-Oriented Programming

Python
# Class definition
class Person:
    # Class variable
    species = "Homo sapiens"
    
    # Constructor
    def __init__(self, name, age):
        self.name = name      # Instance variable
        self.age = age
        self._protected = "Protected"   # Convention for protected
        self.__private = "Private"      # Name mangling for private
    
    # Instance method
    def greet(self):
        return f"Hello, I'm {self.name}"
    
    # String representation
    def __str__(self):
        return f"Person({self.name}, {self.age})"
    
    # Class method
    @classmethod
    def create_anonymous(cls):
        return cls("Anonymous", 0)
    
    # Static method
    @staticmethod
    def is_adult(age):
        return age >= 18

# Inheritance
class Employee(Person):
    def __init__(self, name, age, salary):
        super().__init__(name, age)
        self.salary = salary
    
    def greet(self):  # Method overriding
        return f"Hello, I'm {self.name}, an employee"

# Usage
p = Person("Alice", 25)
print(p.greet())
print(Person.is_adult(20))

e = Employee("Bob", 30, 50000)
print(e.greet())

File Handling

Python
# Writing to file
with open("example.txt", "w") as f:
    f.write("Hello, World!\n")
    f.writelines(["Line 1\n", "Line 2\n"])

# Reading from file
with open("example.txt", "r") as f:
    content = f.read()          # Read entire file
    
with open("example.txt", "r") as f:
    lines = f.readlines()       # Read all lines as list
    
with open("example.txt", "r") as f:
    for line in f:              # Read line by line
        print(line.strip())

# Append to file
with open("example.txt", "a") as f:
    f.write("New line\n")

# Working with JSON
import json

data = {"name": "Alice", "age": 25}

# Write JSON
with open("data.json", "w") as f:
    json.dump(data, f, indent=4)

# Read JSON
with open("data.json", "r") as f:
    loaded_data = json.load(f)

Exception Handling

Python
# Basic try-except
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

# Multiple exceptions
try:
    num = int(input("Enter number: "))
    result = 10 / num
except ValueError:
    print("Invalid input!")
except ZeroDivisionError:
    print("Cannot divide by zero!")
except Exception as e:
    print(f"Error: {e}")
finally:
    print("This always runs")

# Raising exceptions
def validate_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    return age

# Custom exception
class CustomError(Exception):
    def __init__(self, message):
        self.message = message
        super().__init__(self.message)

raise CustomError("Something went wrong!")

Modules & Packages

Python
# Importing modules
import math
print(math.sqrt(16))        # 4.0

from math import pi, sqrt
print(pi)                   # 3.14159...

from math import *          # Import all (not recommended)

import numpy as np          # Alias

# Popular built-in modules
import os               # Operating system
import sys              # System-specific
import datetime         # Date and time
import random           # Random numbers
import re               # Regular expressions
import collections      # Specialized containers

# Creating your own module (mymodule.py)
# def greet(name):
#     return f"Hello, {name}!"

# Using it
# from mymodule import greet
# print(greet("Alice"))

# Package structure
# mypackage/
#     __init__.py
#     module1.py
#     module2.py
#     subpackage/
#         __init__.py
#         module3.py
Must-Know Python Libraries:
NumPy: Numerical computing
Pandas: Data manipulation
Matplotlib: Data visualization
Requests: HTTP requests
Flask/Django: Web frameworks