PythonEssential
3 —syntax,
Beginner Cheat Sheet
data structures, and patterns
Variables & Data Types
name = "Alice" # str
age = 30 # int
price = 9.99 # float
is_active = True # bool
nothing = None # NoneType
Python is dynamically typed — you don't need to declare types.
String Operations
s = "Hello, World!"
print([Link]()) # HELLO, WORLD!
print(s[0:5]) # Hello
print(len(s)) # 13
print(f"Hi, {name}!") # Hi, Alice!
f-strings (Python 3.6+) are the preferred way to format strings.
Lists
fruits = ["apple", "banana", "cherry"]
[Link]("date") # add to end
[Link](0) # remove first
print(fruits[1]) # banana
print(len(fruits)) # 3
Lists are ordered, mutable, and allow duplicate values.
Dictionaries
person = {"name": "Bob", "age": 25}
print(person["name"]) # Bob
person["email"] = "b@[Link]" # add key
for k, v in [Link]():
print(k, "->", v)
Dictionaries store key-value pairs. Keys must be unique.
Control Flow
if age >= 18:
print("Adult")
elif age >= 13:
print("Teen")
else:
print("Child")
for i in range(5):
print(i) # 0 1 2 3 4
Indentation (4 spaces) defines code blocks in Python.
Functions
def greet(name, greeting="Hello"):
"""Return a greeting string."""
return f"{greeting}, {name}!"
print(greet("Alice")) # Hello, Alice!
print(greet("Bob", "Hi")) # Hi, Bob!
Use default arguments to make parameters optional.
List Comprehensions
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
List comprehensions are concise and often faster than for-loops.
Error Handling
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
finally:
print("This always runs")
Always handle specific exceptions rather than bare except clauses.