Python Syntax Cheat Sheet: Variables to Classes with Runnable Examples & 5 Common Pitfalls
This comprehensive Python syntax reference covers ten core topics from variables and strings to classes, providing runnable code examples for each concept plus five frequently confused pitfalls like mutable default arguments and shallow copying.
Variables & Basic Types
Python is dynamically typed; variables are created on assignment without declaration.
name = "小明" # str
age = 18 # int
height = 1.75 # float
is_student = True # bool
nothing = None # NoneTypeType conversion is common when handling API responses or file input:
int("123") # 123
str(456) # "456"
float("3.14") # 3.14
list("abc") # ['a', 'b', 'c']Use type(x) to inspect type, but prefer isinstance(x, int) for type checks because it respects inheritance — e.g., True is considered an int subclass, a pitfall only isinstance reveals.
String Operations (Highest Frequency)
s = " Hello, Python "
s.strip() # remove leading/trailing spaces -> "Hello, Python"
s.lower() # lowercase
s.upper() # uppercase
s.replace("Hello", "Hi")
s.split(",") # -> [' Hello', ' Python ']
"-".join(["a", "b"]) # -> "a-b"
s.startswith(" He") # prefix check
s.find("Python") # returns index, -1 if not foundsplitand join are inverse operations: splitting yields a list, joining requires an explicit separator.
Most common pitfall: forgetting that string methods return new strings. Strings are immutable; s.strip() does not modify s — you must reassign:
s.strip() # does nothing, s unchanged
s = s.strip() # correctFormatting: f-strings are now recommended over % and .format() for clarity:
print(f"I am {name}, {age} years old")
print(f"Result: {3.14159:.2f}") # keeps two decimals -> 3.14Format specifiers like :.2f are used daily in reports, logs, and monetary values.
Lists, Dictionaries, Sets
List: ordered, mutable
nums = [3, 1, 2]
nums.append(4) # append at end
nums.insert(0, 0) # insert at index
nums.sort() # in-place sort
nums.reverse() # reverse in-place
len(nums) # length
nums[0] # first element
nums[-1] # last element
nums[1:3] # slicesort()mutates the list and returns None; nums = nums.sort() would set nums to None. Use sorted(nums) to get a new sorted list.
Dictionary: key-value pairs
user = {"name": "小明", "age": 18}
user["city"] = "北京" # add new key
user.get("age") # returns value or None
user.get("phone", "未填") # default if missing
user.keys() # all keys
user.values() # all values
user.items() # key-value pairs
for k, v in user.items():
print(k, v)Prefer get() for value access. user["phone"] raises KeyError on missing keys; get() returns None or a provided default, avoiding verbose try blocks when processing external data.
Since Python 3.7, dictionaries preserve insertion order, so iteration order is predictable.
Set: deduplication, unordered
a = {1, 2, 3}
b = {2, 3, 4}
a & b # intersection {2, 3}
a | b # union {1, 2, 3, 4}
a - b # difference {1}Fastest deduplication: list(set(my_list)). Trade-off: order is lost. To preserve order, use dict.fromkeys(my_list).
Comprehensions: Python's Soul
List comprehensions condense "loop + append" into one line:
squares = [x * x for x in range(5)] # [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0]Dictionary and set comprehensions follow the same pattern:
d = {x: x * x for x in range(3)} # {0: 0, 1: 1, 2: 4}
s = {x % 3 for x in range(10)}Remember the positional rule: expression first, condition after. In [x for x in nums if x > 0], x is the output, if x > 0 is the filter.
Nesting is supported, but readability comes first; beyond two levels, plain loops are easier to maintain.
Conditionals & Loops
# Ternary expression
level = "adult" if age >= 18 else "minor"
# Iteration
for i in range(3): # 0 1 2
print(i)
for i, v in enumerate(["a", "b"]): # with index
print(i, v)
for a, b in zip([1, 2], ["x", "y"]): # parallel iteration
print(a, b)
count = 0
while count < 3:
count += 1enumerateand zip are the first two functions to reach for in loops — they eliminate manual index counters and parallel list indexing.
A lesser-known construct: for ... else. The else block runs only if the loop completes without a break, ideal for "search and handle not-found" logic without flag variables:
for user in users:
if user["id"] == target:
print("Found")
break
else:
print("Not found")Functions
def greet(name, greeting="你好"): # default parameter
return f"{greeting},{name}"
greet("小明") # 你好,小明
greet("小明", "早上好") # 早上好,小明Variable arguments:
def add(*args): # arbitrary positional args -> tuple
return sum(args)
def show(**kwargs): # arbitrary keyword args -> dict
print(kwargs)*argscollects into a tuple, **kwargs into a dict; at call sites, * unpacks a list, ** unpacks a dict. lambda is handy for sorting keys:
data = [{"name": "a", "age": 20}, {"name": "b", "age": 18}]
data.sort(key=lambda x: x["age"])Major pitfall: never use mutable objects as default arguments.
def add_item(item, box=[]): # wrong
box.append(item)
return box
add_item(1) # [1]
add_item(2) # [1, 2] unexpectedDefault values are evaluated once at function definition, so all calls share the same list. Correct pattern:
def add_item(item, box=None):
if box is None:
box = []
box.append(item)
return boxException Handling
try:
result = 10 / 0
except ZeroDivisionError as e:
print("Division by zero:", e)
except Exception as e:
print("Other error:", e)
else:
print("No exception")
finally:
print("Always runs")elseholds code that should run only when no exception occurs; finally holds cleanup (close files, release connections).
Never write bare except: . It swallows Ctrl+C (KeyboardInterrupt), making debugging impossible. At minimum use except Exception as e and log e.
File I/O
with open("test.txt", "w", encoding="utf-8") as f:
f.write("Hello
")
with open("test.txt", "r", encoding="utf-8") as f:
content = f.read()
with open("test.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())withensures automatic closing, preventing forgotten close() calls.
Two habits to adopt:
Always specify encoding="utf-8" . Windows defaults to GBK, causing Chinese text to fail.
Prefer line-by-line iteration over read() . For large files, memory usage differs by orders of magnitude.
Common Built-in Functions
len(x) # length
sum([1,2,3]) # sum -> 6
max([1,3,2]) # maximum
min([1,3,2]) # minimum
sorted([3,1,2]) # returns new sorted list
reversed(x) # reverse iterator
any([False, True]) # True if any element truthy
all([True, True]) # True only if all truthy
map(str, [1,2,3]) # map -> ['1','2','3']
filter(None, [0,1,2]) # filter out falsy valuesany/ all excel at batch validation, e.g., all(bool(v) for v in values) checks that all fields are non-empty.
Note: map and filter return iterators, not lists. Wrap with list(...) to materialize; otherwise printing shows an iterator object.
Basic Class Syntax
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return f"I am {self.name}, {self.age} years old"
p = Person("小明", 18)
print(p.introduce())__init__assigns instance attributes; the first method parameter is conventionally self (not a keyword, but changing it hurts readability).
Advanced features — inheritance, @property, @staticmethod, __str__ — can be learned after mastering the basics.
Five Most Confusing Points
Mutable default arguments: def f(a=[]) shares the same list across calls; use None and initialize inside.
is vs == : == compares values, is compares object identity. Use is None for null checks; never use is for string comparison.
sort() vs sorted() : sort() mutates in-place and returns None; sorted() returns a new list.
Shallow copy: b = a is just another reference; b = a[:] or a.copy() creates a new list, but nested elements remain shared.
Deleting list elements during iteration: causes skipped items; rebuild via comprehension or iterate backwards.
Summary
Strings are immutable: strip(), replace() must capture return values — the most frequent beginner error.
Use dict.get() for dictionary access: avoids KeyError, provides defaults, critical for external data.
Memorize comprehension structure: expression first, condition after; drop back to loops beyond two levels.
Never use mutable defaults: [] and {} leak state across calls.
Always specify encoding in file operations: Windows defaults to GBK, the top cross-platform script failure.
Syntax isn't hard; fluency is. Treat this as a cheat sheet — glance back when uncertain instead of searching docs repeatedly.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
