Python Cheatsheet
10xdev.blog/cheatsheets
# 1. Basics
# 1. Variables and Data Types
name: str = "Alice"
age: int = 30
height: float = 1.75
is_student: bool = True
fruits: list = ["apple", "banana"]
coordinates: tuple = (10, 20)
person: dict = {"name": "Bob", "age": 25}
unique_numbers: set = {1, 2, 3}

# f-string formatting
print(f"Name: {name}, Age: {age}")

# Operators (Arithmetic, Comparison, Logical)
a, b = 10, 3
print(f"a + b = {a + b}")  # Addition
print(f"a > b is {a > b}") # Comparison
print(f"a > 0 and b > 0 is {a > 0 and b > 0}") # Logical
# 2. Control Flow
# if/elif/else
age = 20
if age < 18:
    print("Minor")
elif 18 <= age < 65:
    print("Adult")
else:
    print("Senior")

# For loop
for i in range(3):
    print(f"For loop count: {i}")

# While loop
count = 0
while count < 3:
    print(f"While loop count: {count}")
    count += 1

# Break and Continue
for i in range(5):
    if i == 2:
        continue  # Skip this iteration
    if i == 4:
        break     # Exit the loop
    print(f"Loop item: {i}")
# 3. Data Structures
# Lists (mutable, ordered)
my_list = [1, "a", 3.14]
my_list.append(4)
print(f"List: {my_list}, First element: {my_list[0]}")

# Tuples (immutable, ordered)
my_tuple = (1, "a", 3.14)
print(f"Tuple: {my_tuple}, Second element: {my_tuple[1]}")

# Dictionaries (mutable, key-value pairs)
my_dict = {"name": "Alice", "age": 30}
my_dict["city"] = "New York"
print(f"Dict: {my_dict}, Name: {my_dict['name']}")

# Sets (mutable, unordered, unique elements)
my_set = {1, 2, 2, 3}
my_set.add(4)
print(f"Set: {my_set}")
# 4. Comprehensions
# List Comprehension
squares = [x**2 for x in range(5)]
print(f"Squares: {squares}") # [0, 1, 4, 9, 16]

# Dictionary Comprehension
sq_dict = {x: x**2 for x in range(3)}
print(f"Square dict: {sq_dict}") # {0: 0, 1: 1, 2: 4}

# Set Comprehension
sq_set = {x**2 for x in range(3)}
print(f"Square set: {sq_set}") # {0, 1, 4}

# Generator Expression
sq_gen = (x**2 for x in range(3))
print(f"Square generator: {list(sq_gen)}")
# 5. Functions
# Basic function with type hints
def greet(name: str) -> str:
    return f"Hello, {name}!"

# Function with default arguments
def power(base: float, exp: float = 2) -> float:
    return base ** exp

# Function with variable arguments
def summarize(*args, **kwargs):
    arg_sum = sum(args)
    print(f"Sum of args: {arg_sum}")
    for key, value in kwargs.items():
        print(f"{key}: {value}")

summarize(1, 2, 3, name="Alice", status="active")

# Lambda (anonymous) function
multiply = lambda a, b: a * b
print(f"Lambda result: {multiply(5, 4)}")
# 6. Object-Oriented Programming
class Animal:
    def __init__(self, name: str):
        self.name = name

    def speak(self) -> str:
        raise NotImplementedError("Subclass must implement abstract method")

    def __str__(self) -> str:
        return f"An animal named {self.name}"

# Inheritance
class Dog(Animal):
    def speak(self) -> str:
        return "Woof!"

my_dog = Dog("Buddy")
print(my_dog.speak()) # Woof!
print(my_dog)       # An animal named Buddy
# 7. Error Handling
try:
    # result = 10 / 0
    raise ValueError("This is a custom error")
except ZeroDivisionError:
    print("Error: Cannot divide by zero!")
except ValueError as e:
    print(f"Caught a value error: {e}")
finally:
    print("This block always executes.")
# 8. File I/O with Context Managers
# Writing to a file
try:
    with open("example.txt", "w") as f:
        f.write("Hello, World!\n")
except IOError as e:
    print(f"Error writing to file: {e}")

# Reading from a file
try:
    with open("example.txt", "r") as f:
        content = f.read()
        print(f"File content: {content.strip()}")
except FileNotFoundError:
    print("File not found.")
# 9. Standard Library Highlights
import os
import json
import re
from collections import defaultdict

# os: Interact with the operating system
print(f"Current dir: {os.getcwd()}")

# json: Work with JSON data
person_dict = {'name': 'Alice', 'age': 30}
person_json = json.dumps(person_dict)
print(f"JSON: {person_json}")

# re: Regular expressions
match = re.search(r'\w+', 'hello world')
if match:
    print(f"Regex match: {match.group(0)}") # 'hello'

# collections: High-performance container datatypes
dd = defaultdict(int)
dd['a'] += 1
print(f"Defaultdict: {dd['a']}, {dd['b']}") # 1, 0
# 10. Environment & Packaging
# 1. Create a virtual environment
python3 -m venv myenv

# 2. Activate the environment
# On macOS/Linux:
source myenv/bin/activate
# On Windows:
# .\myenv\Scripts\activate

# 3. Install packages with pip
pip install requests

# 4. Freeze dependencies to requirements.txt
pip freeze > requirements.txt

# 5. Install from requirements.txt
pip install -r requirements.txt

# 6. Deactivate
deactivate
master* 0 0