Basics
Shared from "Python" on Inkdown
Python Basics (Engineer Cheat Sheet)
Environment & Tooling
pyenv + venv
pyenv is a Python version manager, similar to nvm for Node.js.
- It helps you install and switch between multiple Python versions.
venv creates an isolated environment for one project, so packages from one project do not affect another.
Basics
Bash
pyenv install 3.11.6
pyenv local 3.11.6
python -m venv venv
source venv/bin/activate
venv\Scripts\activate
pip + requirements.txt
pip is Python’s package installer.
requirements.txt stores the list of dependencies for a project.
- This makes it easy for others, or your future self, to install the same packages.
Bash
pip install fastapi
pip freeze > requirements.txt
pip install -r requirements.txt
Poetry (pyproject.toml)
- Poetry is a modern dependency and project manager for Python.
- It handles dependencies, virtual environments, and package configuration in one place.
pyproject.toml is the main config file Poetry uses.
Bash
poetry init
poetry add fastapi
poetry install
Python REPL + ipython
- REPL means Read-Eval-Print Loop.
- It is a quick interactive shell where you can test Python code.
ipython is a better REPL with autocomplete, command history, and nicer output.
Bash
python
>>> 2 + 2
ipython
In [1]: 2 + 2
Syntax — 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.
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.
Python
def add(a: int, b: int) -> int:
return a + b
f-strings
- f-strings are the cleanest way to insert variables into strings.
- Put
f before the string, then use {} inside it.
Python
name = "Shubho"
age = 21
print(f"My name is {name} and I am {age} years old.")
None vs null / undefined
- Python has
None to represent “no value”.
- There is no separate
null or undefined.
- The correct check is
is None, not == None.
Python
x = None
if x is None:
print("x has no value")
Truthiness
- In Python, some values are treated as
False in conditions.
- Common falsy values are:
None, 0, "", [], {}, set().
- Most other values are truthy.
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.
Python
if (length := len("python")) > 5:
print(length)
Collections & Comprehensions
list / dict / set / tuple
list: ordered, mutable collection
dict: key-value mapping
set: unordered collection of unique values
tuple: ordered, immutable collection
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.
Python
nums = [1, 2, 3, 4, 5]
squares = [n * n for n in nums]
print(squares)
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.
Python
nums = [1, 2, 3]
squares = {n: n * n for n in nums}
print(squares)
Unpacking *args and **kwargs
*args collects extra positional arguments into a tuple.
**kwargs collects extra keyword arguments into a dictionary.
- Useful when you do not know how many arguments will be passed.
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.
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.
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.
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.
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__.
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__.
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.
Python
with open("notes.txt", "r") as file:
content = file.read()
print(content)
Error Handling & Modules
try / except / finally
try contains code that may fail.
except handles the error.
finally always runs, whether there was an error or not.
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.
Python
class AppError(Exception):
pass
raise AppError("Something went wrong in the app")
Imports
import lets you use code from another file or module.
- This helps organize code into reusable parts.
Python
import math
print(math.sqrt(16))
__init__.py
__init__.py tells 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.py
Python
from mypackage.utils import my_function
Mental 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.
Everything is an object
- Numbers, strings, functions, classes, everything in Python is an object.
- That is why Python feels very consistent.
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.