🐍 Python Cheatsheet (Beginner → Advanced)

← Go Back

1. What is Python?

Python is a high-level, interpreted programming language known for readability and versatility.

Purpose: Write clear, logical code for projects big and small.

2. Basic Data Types

is_active = True
age = 30
pi = 3.1415
name = "Alice"
items = [1, 2, 3]
info = {"key": "value"}
data = None

Purpose: Store different types of data appropriately.

3. Variables and Type Inference

message = "Hello World"  # Python infers the type

Purpose: Write clean code without explicit type declarations.

4. Functions

def add(a, b):
    return a + b

Purpose: Reuse logic without repeating code.

5. Control Flow

if age > 18:
    print("Adult")
elif age == 18:
    print("Just became adult")
else:
    print("Minor")

Purpose: Make decisions based on conditions.

6. Loops

for item in items:
    print(item)

while age > 0:
    age -= 1

Purpose: Repeat actions multiple times.

7. List Comprehension

squares = [x**2 for x in range(5)]

Purpose: Create lists quickly and concisely.

8. Dictionaries

person = {"name": "Alice", "age": 30}
print(person["name"])

Purpose: Store key-value pairs for quick lookup.

9. Classes and Objects

class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print(f"Hello, {self.name}")

p = Person("Alice")
p.greet()

Purpose: Organize code using Object-Oriented Programming (OOP).

10. Inheritance

class Student(Person):
    def __init__(self, name, grade):
        super().__init__(name)
        self.grade = grade

Purpose: Reuse and extend functionality across classes.

11. Modules and Packages

# math_module.py
def add(a, b):
    return a + b

# app.py
import math_module
print(math_module.add(2, 3))

Purpose: Organize and reuse code across multiple files.

12. Exception Handling

try:
    1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
finally:
    print("End of operation")

Purpose: Handle errors gracefully without crashing.

13. Decorators

def decorator(func):
    def wrapper():
        print("Before function")
        func()
        print("After function")
    return wrapper

@decorator
def greet():
    print("Hello")

greet()

Purpose: Extend or modify function behavior.

14. Lambda Functions

add = lambda x, y: x + y
print(add(2, 3))

Purpose: Create small anonymous functions inline.

15. Built-in Functions to Know

nums = [1, 2, 3]
doubled = list(map(lambda x: x*2, nums))

Purpose: Perform common tasks easily.

16. Type Annotations

def greet(name: str) -> str:
    return f"Hello, {name}"

Purpose: Improve code readability and tooling support.

17. Virtual Environments

python -m venv myenv
source myenv/bin/activate  # Mac/Linux
myenv\Scripts\activate    # Windows

Purpose: Isolate project dependencies.

18. Popular Libraries

Purpose: Extend Python capabilities quickly.

Bonus Tips