Data Types
- str"hello", 'world'
- int42, -7
- float3.14, -0.5
- boolTrue, False
- list[1, 2, 3]
- dict{"a": 1, "b": 2}
- tuple(1, 2, 3)
- set{1, 2, 3}
String Methods
- s.upper()Uppercase
- s.lower()Lowercase
- s.strip()Remove whitespace
- s.split(",")Split to list
- ",".join(list)Join list
- s.replace(a, b)Replace text
- s.startswith()Starts with
List Methods
- lst.append(x)Add to end
- lst.insert(i, x)Insert at index
- lst.pop()Remove last
- lst.remove(x)Remove first x
- lst.sort()Sort in place
- lst.reverse()Reverse in place
- len(lst)Get length
Dict Methods
- d.get(k, default)Safe get
- d.keys()All keys
- d.values()All values
- d.items()Key-value pairs
- d.update(d2)Merge dicts
- d.pop(k)Remove key
Control Flow
# If/elif/else
if condition:
do_something()
elif other_condition:
do_other()
else:
do_default()
# For loop
for item in items:
print(item)
# For with index
for i, item in enumerate(items):
print(i, item)
# While loop
while condition:
do_something()
Functions & Lambda
# Function definition
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
# *args and **kwargs
def func(*args, **kwargs):
for arg in args:
print(arg)
for k, v in kwargs.items():
print(k, v)
# Lambda function
square = lambda x: x ** 2
List Comprehensions
# Basic
[x * 2 for x in range(10)]
# With condition
[x for x in nums if x > 0]
# Dict comprehension
{k: v for k, v in items}
# Set comprehension
{x * 2 for x in nums}
File Operations
# Read file
with open("file.txt") as f:
content = f.read()
# Write file
with open("file.txt", "w") as f:
f.write("text")
# Read lines
for line in f:
print(line)
Built-in Functions
- len()Length
- range()Number sequence
- type()Get type
- isinstance()Check type
- sorted()Return sorted
- zip()Combine iterables
- map(fn, iter)Apply function
- filter(fn, iter)Filter items
Exception Handling
try:
risky_operation()
except ValueError as e:
print(f"Error: {e}")
except Exception:
print("Unknown error")
else:
print("Success!")
finally:
cleanup()
F-Strings
name = "World"
num = 3.14159
# Basic
f"Hello, {name}!"
# Formatting
f"{num:.2f}" # "3.14"
f"{num:10.2f}" # " 3.14"
# Expressions
f"{2 + 2}" # "4"