Basics
Last updated on April 5, 2026
Python Basics (Engineer Cheat Sheet)
Environment & Tooling
pyenv + venv
pyenvis a Python version manager, similar tonvmfor Node.js.- It helps you install and switch between multiple Python versions.
venvcreates an isolated environment for one project, so packages from one project do not affect another.
Example:
Bash
pyenv install 3.11.6
pyenv local 3.11.6
python -m venv venv
source venv/bin/activate # macOS / Linux
venv\Scripts\activate # Windowspip + requirements.txt
pipis Python’s package installer.requirements.txtstores the list of dependencies for a project.- This makes it easy for others, or your future self, to install the same packages.
Example:
Bash
pip install fastapi
pip freeze > requirements.txt
pip install -r requirements.txtPoetry (pyproject.toml)
- Poetry is a modern dependency and project manager for Python.
- It handles dependencies, virtual environments, and package configuration in one place.
pyproject.tomlis the main config file Poetry uses.
Example:
Bash
poetry init
poetry add fastapi
poetry installPython REPL + ipython
- REPL means Read-Eval-Print Loop.
- It is a quick interactive shell where you can test Python code.
ipythonis a better REPL with autocomplete, command history, and nicer output.
Example:
Bash
python
>>> 2 + 2
ipython
In [1]: 2 + 2Syntax — What’s Different from TS/JS
Indentation, no braces
- Python uses indentation to define code blocks.
- It does not use
{}like JavaScript or TypeScript. - A colon
:starts a new block.
Example:
Python
if x > 10:
print("big")
else:
print("small")Type hints
- Type hints let you describe what type a variable or function argument should be.
- They make code easier to understand and improve editor support.
- They are not strictly enforced by Python at runtime by default.
Example:
Python
def add(a: int, b: int) -> int:
return a + bf-strings
- f-strings are the cleanest way to insert variables into strings.
- Put
fbefore the string, then use{}inside it.
Example:
Python
name = "Shubho"
age = 21
print(f"My name is {name} and I am {age} years old.")None vs null / undefined
- Python has
Noneto represent “no value”. - There is no separate
nullorundefined. - The correct check is
is None, not== None.
Example:
Python
x = None
if x is None:
print("x has no value")Truthiness
- In Python, some values are treated as
Falsein conditions. - Common falsy values are:
None,0,"",[],{},set(). - Most other values are truthy.
Example:
Python
items = []
if items:
print("has items")
else:
print("empty")Walrus operator :=
- The walrus operator assigns a value and uses it in the same expression.
- It is useful when you want to avoid doing the same work twice.
Example:
Python
if (length := len("python")) > 5:
print(length)Collections & Comprehensions
list / dict / set / tuple
list: ordered, mutable collectiondict: key-value mappingset: unordered collection of unique valuestuple: ordered, immutable collection
Example:
Python
my_list = [1, 2, 3]
my_dict = {"name": "Shubho", "age": 21}
my_set = {1, 2, 3}
my_tuple = (1, 2, 3)List comprehensions
- A compact way to create lists from loops.
- Very common and very Pythonic.
Example:
Python
nums = [1, 2, 3, 4, 5]
squares = [n * n for n in nums]
print(squares)With condition:
Python
evens = [n for n in nums if n % 2 == 0]
print(evens)Dict comprehensions
- Similar to list comprehensions, but for dictionaries.
- Useful when transforming data into key-value form.
Example:
Python
nums = [1, 2, 3]
squares = {n: n * n for n in nums}
print(squares)Unpacking *args and **kwargs
*argscollects extra positional arguments into a tuple.**kwargscollects extra keyword arguments into a dictionary.- Useful when you do not know how many arguments will be passed.
Example:
Python
def show(*args, **kwargs):
print(args)
print(kwargs)
show(1, 2, 3, name="Shubho", role="Engineer")Generators (yield)
- A generator returns values one at a time instead of all at once.
- This makes it memory-efficient.
- It is useful for large data, streams, and lazy processing.
Example:
Python
def count_up_to(n):
for i in range(1, n + 1):
yield i
for num in count_up_to(3):
print(num)Functions & OOP
Default args, keyword args
- Default arguments give a parameter a fallback value.
- Keyword arguments let you pass values by name.
- This makes function calls clearer and more flexible.
Example:
Python
def greet(name, message="Hello"):
print(f"{message}, {name}")
greet("Shubho")
greet("Shubho", message="Welcome")Keyword-only arguments
- You can force some arguments to be passed by name using
*. - This makes calls more explicit and avoids confusion.
Example:
Python
def create_user(name, *, admin=False):
print(name, admin)
create_user("Shubho", admin=True)Decorators
- A decorator wraps a function and changes or extends its behavior.
- Common uses: logging, authentication, caching, route handling.
Example:
Python
def log_call(fn):
def wrapper():
print("Function is running")
return fn()
return wrapper
@log_call
def say_hi():
print("Hi")
say_hi()dataclass
- A dataclass is a simpler way to write classes that mostly store data.
- It automatically creates methods like
__init__and__repr__.
Example:
Python
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int
user = User("Shubho", 21)
print(user)Dunder methods
- Dunder means “double underscore”.
- These special methods let your class behave in custom ways.
- Examples:
__init__,__str__,__len__,__getitem__.
Example:
Python
class Book:
def __init__(self, title):
self.title = title
def __str__(self):
return f"Book: {self.title}"
book = Book("Python Basics")
print(book)Context managers (with)
- A context manager handles setup and cleanup automatically.
- It is commonly used for files, database connections, and locks.
- Even if an error happens, cleanup still runs.
Example:
Python
with open("notes.txt", "r") as file:
content = file.read()
print(content)Error Handling & Modules
try / except / finally
trycontains code that may fail.excepthandles the error.finallyalways runs, whether there was an error or not.
Example:
Python
try:
num = int("abc")
except ValueError as e:
print("Conversion failed:", e)
finally:
print("This always runs")Custom exceptions
- You can create your own exception types for clearer error handling.
- This makes bigger applications easier to maintain.
Example:
Python
class AppError(Exception):
pass
raise AppError("Something went wrong in the app")Imports
importlets you use code from another file or module.- This helps organize code into reusable parts.
Example:
Python
import math
print(math.sqrt(16))__init__.py
__init__.pytells Python that a folder should behave like a package.- It can also run package setup code or expose selected imports.
Example folder structure:
Python
mypackage/
__init__.py
utils.pyImport example:
Python
from mypackage.utils import my_functionMental Model
Python is interpreted
- Python code is executed by the Python interpreter.
- You do not usually compile it manually like C or C++.
Python is dynamically typed
- You do not need to declare variable types beforehand.
- A variable can point to different types of values over time.
Example:
Python
x = 10
x = "hello"Everything is an object
- Numbers, strings, functions, classes, everything in Python is an object.
- That is why Python feels very consistent.
Example:
Python
x = "hello"
print(type(x))Clean code matters a lot in Python
- Python is built around readability.
- Simple, clear code is preferred over clever but confusing code.
What to Learn Next
async / await
- Used for asynchronous programming.
- Important for APIs, web servers, and I/O-heavy systems.
FastAPI
- A modern Python web framework.
- Great for building APIs quickly.
Pydantic
- Used for validation and structured data handling.
- Common in FastAPI apps.
File handling and streams
- Important for working with files, uploads, logs, and data pipelines.
Concurrency
- Learn the difference between threads, processes, and async tasks.
Packaging and deployment
- Important for shipping real Python applications.