← Back to Home
🐍
Programming Languages

Python

Python syntax, built-in functions, and common patterns

📦 Data Types

Command Description
int Integer numbers: 42, -17, 0
float Decimal numbers: 3.14, -0.5
str Text strings: "hello", 'world'
bool Boolean: True, False
list Ordered mutable sequence: [1, 2, 3]
tuple Ordered immutable sequence: (1, 2, 3)
dict Key-value pairs: {"a": 1, "b": 2}
set Unique unordered items: {1, 2, 3}
None Null/empty value

📝 String Methods

Command Description
s.upper() Convert to uppercase
s.lower() Convert to lowercase
s.strip() Remove leading/trailing whitespace
s.split(sep) Split string into list
s.join(list) Join list into string
s.replace(old, new) Replace substring
s.find(sub) Find substring index (-1 if not found)
s.startswith(pre) Check if starts with prefix
s.endswith(suf) Check if ends with suffix
f"Hello {name}" F-string formatting

📋 List Methods

Command Description
list.append(x) Add item to end
list.extend(iter) Add all items from iterable
list.insert(i, x) Insert item at index
list.remove(x) Remove first occurrence of x
list.pop(i) Remove and return item at index
list.sort() Sort list in place
list.reverse() Reverse list in place
list.index(x) Find index of first occurrence
list.count(x) Count occurrences of x
list[start:end:step] Slice list

🔑 Dictionary Methods

Command Description
d.keys() Get all keys
d.values() Get all values
d.items() Get all key-value pairs
d.get(key, default) Get value with default
d.pop(key) Remove and return value
d.update(dict2) Merge another dictionary
d.setdefault(key, val) Set if key missing
key in d Check if key exists

🔀 Control Flow

Command Description
if / elif / else Conditional branching
for x in iterable: Iterate over sequence
while condition: Loop while condition true
break Exit loop immediately
continue Skip to next iteration
pass Do nothing (placeholder)
match value: case x: Pattern matching (3.10+)

⚙️ Functions

Command Description
def func(args): Define function
return value Return value from function
lambda x: x * 2 Anonymous function
*args Variable positional arguments
**kwargs Variable keyword arguments
@decorator Function decorator
def func() -> int: Type hint for return

🛠️ Built-in Functions

Command Description
len(x) Get length of sequence
range(start, stop, step) Generate number sequence
enumerate(iter) Get index and value pairs
zip(iter1, iter2) Pair items from iterables
map(func, iter) Apply function to all items
filter(func, iter) Filter items by function
sorted(iter) Return sorted list
reversed(iter) Return reversed iterator
sum(iter) Sum all numbers
min(iter) / max(iter) Get minimum/maximum
any(iter) / all(iter) Check if any/all true
isinstance(obj, type) Check object type
type(obj) Get object type
print() Output to console
input() Read user input
open(file, mode) Open file for reading/writing

Comprehensions

Command Description
[x for x in iter] List comprehension
[x for x in iter if cond] List with condition
{x for x in iter} Set comprehension
{k: v for k, v in iter} Dict comprehension
(x for x in iter) Generator expression

📁 File I/O

Command Description
open(f, "r") Open for reading
open(f, "w") Open for writing (overwrite)
open(f, "a") Open for appending
with open(f) as file: Context manager (auto-close)
file.read() Read entire file
file.readline() Read one line
file.readlines() Read all lines as list
file.write(s) Write string to file

⚠️ Exception Handling

Command Description
try: / except: Catch exceptions
except Error as e: Catch specific exception
finally: Always execute (cleanup)
raise Exception(msg) Raise exception
assert condition Assert condition is true

📝 Common Patterns

# List comprehension with condition
evens = [x for x in range(10) if x % 2 == 0]

# Dictionary from two lists
d = dict(zip(keys, values))

# Read file lines
with open("file.txt") as f:
lines = f.readlines()

# Lambda with map
doubled = list(map(lambda x: x * 2, numbers))

# Ternary expression
result = "yes" if condition else "no"

# Unpack values
a, b, *rest = [1, 2, 3, 4, 5]

# Walrus operator (3.8+)
if (n := len(data)) > 10:
print(f"Got {n} items")