Python Basics Quick Reference¶
A concise overview of common Python syntax and patterns. Use this as a refresher when writing simple scripts or reviewing key language features.
Variables and Types¶
- Assign variables with
= - Basic types:
int,float,str,bool - Multiple assignment:
x, y = 1, 2 - Type conversion:
int("3"),float("3.14")
my_int: int = 5
my_float: float = 3.14
my_str: str = "hello"
my_bool: bool = True
Collections¶
- List: ordered, mutable
- Tuple: ordered, immutable
- Dictionary: key–value store
- Set: unordered unique items
colors: list[str] = ["red", "green", "blue"]
point: tuple[int, int] = (3, 4)
config: dict[str, str] = {"host": "localhost", "port": "8080"}
tags: set[str] = {"python", "basics"}
Control Flow¶
# Conditional
if condition:
...
elif other_condition:
...
else:
...
# Looping
for item in iterable:
...
while expression:
...
graph TD;
A[Start] --> B{Condition?};
B -- Yes --> C[Execute body];
C --> B;
B -- No --> D[Continue];
Functions¶
- Define with
def - Document using triple-quoted docstrings
- Default and keyword arguments
- Return values with
return
def greet(name: str, excited: bool = False) -> str:
"""Return a friendly greeting for ``name``.
Args:
name (str): Person to greet.
excited (bool, optional): Add an exclamation if ``True``.
Returns:
str: Personalized greeting.
"""
base = f"Hello, {name}"
return base + "!" if excited else base
Modules and Imports¶
import math
from pathlib import Path
Use if __name__ == "__main__": to run code when a file executes directly.
Exceptions¶
try:
risky_operation()
except ValueError as err:
print(f"Problem: {err}")
Basic I/O¶
user_input = input("Enter value: ")
print("You typed", user_input)