Python notes (4 Part Series)
1 Python Notes #1 – General Introduction
2 Python Notes #2 – Data types
3 Python Notes #3 – Control Flow
4 Python Notes #4 – Functions
Conditional Statements
if, elif, else
Python uses if, elif, and else for decision-making. Conditions are evaluated top-down, and the first true branch executes. Python treats 0, None, [], {}, “”, and False as falsy — everything else is truthy.
Avoid Deep Nesting
# Instead of:if user:if user.is_active:if user.is_admin:do_admin_stuff()# Prefer:if not user or not user.is_active or not user.is_admin:returndo_admin_stuff()# Instead of: if user: if user.is_active: if user.is_admin: do_admin_stuff() # Prefer: if not user or not user.is_active or not user.is_admin: return do_admin_stuff()# Instead of: if user: if user.is_active: if user.is_admin: do_admin_stuff() # Prefer: if not user or not user.is_active or not user.is_admin: return do_admin_stuff()
Enter fullscreen mode Exit fullscreen mode
Use Ternary Expressions for Simple Conditions
status = "active" if user.is_active else "inactive"status = "active" if user.is_active else "inactive"status = "active" if user.is_active else "inactive"
Enter fullscreen mode Exit fullscreen mode
Leverage Truthy/Falsy Evaluations
if items: # Instead of if len(items) > 0process(items)if items: # Instead of if len(items) > 0 process(items)if items: # Instead of if len(items) > 0 process(items)
Enter fullscreen mode Exit fullscreen mode
Use in and not in for Clean Membership Checks
if role in {"admin", "moderator"}:grant_access()if role in {"admin", "moderator"}: grant_access()if role in {"admin", "moderator"}: grant_access()
Enter fullscreen mode Exit fullscreen mode
Looping Constructs
Python offers for and while loops, both supporting an optional else block that runs only if the loop is not exited via break. Useful for search-style logic.
for Loops with range, enumerate, zip
# rangefor i in range(1, 6):print(i)# enumeratefor i, item in enumerate(items, start=1):print(f"{i}: {item}")# zipfor name, score in zip(names, scores):print(f"{name}: {score}")# range for i in range(1, 6): print(i) # enumerate for i, item in enumerate(items, start=1): print(f"{i}: {item}") # zip for name, score in zip(names, scores): print(f"{name}: {score}")# range for i in range(1, 6): print(i) # enumerate for i, item in enumerate(items, start=1): print(f"{i}: {item}") # zip for name, score in zip(names, scores): print(f"{name}: {score}")
Enter fullscreen mode Exit fullscreen mode
while Loop + else
i = 0while i < 5:if should_stop(i):breaki += 1else:print("Completed without break")i = 0 while i < 5: if should_stop(i): break i += 1 else: print("Completed without break")i = 0 while i < 5: if should_stop(i): break i += 1 else: print("Completed without break")
Enter fullscreen mode Exit fullscreen mode
break, continue, pass
for x in data:if x == target:break # Exit loop earlyif x < 0:continue # Skip this iterationprocess(x)def todo():pass # Placeholder for future codefor x in data: if x == target: break # Exit loop early if x < 0: continue # Skip this iteration process(x) def todo(): pass # Placeholder for future codefor x in data: if x == target: break # Exit loop early if x < 0: continue # Skip this iteration process(x) def todo(): pass # Placeholder for future code
Enter fullscreen mode Exit fullscreen mode
Comprehensions with Conditions
Python comprehensions provide a clean and expressive way to build sequences. Conditions can be added inline to filter or transform items.
List Comprehension with if
# Filter even numbersevens = [x for x in nums if x % 2 == 0]# Filter even numbers evens = [x for x in nums if x % 2 == 0]# Filter even numbers evens = [x for x in nums if x % 2 == 0]
Enter fullscreen mode Exit fullscreen mode
List Comprehension with if-else
# Tag even/oddlabels = ["even" if x % 2 == 0 else "odd" for x in nums]# Tag even/odd labels = ["even" if x % 2 == 0 else "odd" for x in nums]# Tag even/odd labels = ["even" if x % 2 == 0 else "odd" for x in nums]
Enter fullscreen mode Exit fullscreen mode
Dict Comprehension with Condition
# Squared values for positives onlysquared = {x: x**2 for x in nums if x > 0}# Squared values for positives only squared = {x: x**2 for x in nums if x > 0}# Squared values for positives only squared = {x: x**2 for x in nums if x > 0}
Enter fullscreen mode Exit fullscreen mode
Set Comprehension with Condition
# Unique lowercase characterschars = {c.lower() for c in text if c.isalpha()}# Unique lowercase characters chars = {c.lower() for c in text if c.isalpha()}# Unique lowercase characters chars = {c.lower() for c in text if c.isalpha()}
Enter fullscreen mode Exit fullscreen mode
Pattern Matching (match-case)
Introduced in Python 3.10, match-case provides cleaner alternatives to long if-elif chains. It supports structural pattern matching, guards, and destructuring.
Basic Matching
match command:case "start":run()case "stop":shutdown()case _:print("Unknown command")match command: case "start": run() case "stop": shutdown() case _: print("Unknown command")match command: case "start": run() case "stop": shutdown() case _: print("Unknown command")
Enter fullscreen mode Exit fullscreen mode
Match with Guards (Conditions)
match user:case {"role": "admin"} if user["active"]:grant_access()case _:deny_access()match user: case {"role": "admin"} if user["active"]: grant_access() case _: deny_access()match user: case {"role": "admin"} if user["active"]: grant_access() case _: deny_access()
Enter fullscreen mode Exit fullscreen mode
Destructuring Tuples / Sequences
match point:case (0, 0):print("Origin")case (x, 0):print(f"X-axis at {x}")case (x, y):print(f"Point at ({x}, {y})")match point: case (0, 0): print("Origin") case (x, 0): print(f"X-axis at {x}") case (x, y): print(f"Point at ({x}, {y})")match point: case (0, 0): print("Origin") case (x, 0): print(f"X-axis at {x}") case (x, y): print(f"Point at ({x}, {y})")
Enter fullscreen mode Exit fullscreen mode
Matching Class Attributes
class User:def __init__(self, name, active): self.name = name; self.active = activematch u:case User(name="admin", active=True):print("Admin is active")class User: def __init__(self, name, active): self.name = name; self.active = active match u: case User(name="admin", active=True): print("Admin is active")class User: def __init__(self, name, active): self.name = name; self.active = active match u: case User(name="admin", active=True): print("Admin is active")
Enter fullscreen mode Exit fullscreen mode
Best Practices & Tips
Use loop-else for Search Logic
The else clause on loops executes only if the loop wasn’t broken. Ideal for search patterns.
for user in users:if user.is_admin:notify(user)breakelse:log("No admin found")for user in users: if user.is_admin: notify(user) break else: log("No admin found")for user in users: if user.is_admin: notify(user) break else: log("No admin found")
Enter fullscreen mode Exit fullscreen mode
Avoid Deep Nesting
Flatten logic by returning early or using guard clauses.
# Deeply nestedif user:if user.active:if user.role == "admin":grant_access()# Cleanerif not user or not user.active or user.role != "admin":returngrant_access()# Deeply nested if user: if user.active: if user.role == "admin": grant_access() # Cleaner if not user or not user.active or user.role != "admin": return grant_access()# Deeply nested if user: if user.active: if user.role == "admin": grant_access() # Cleaner if not user or not user.active or user.role != "admin": return grant_access()
Enter fullscreen mode Exit fullscreen mode
Use Pythonic Alternatives
-
Replace flag variables with early exits
-
Use comprehensions instead of loop-based filtering
-
Use
any()
,all()
,filter()
,map()
where appropriate
# Example: Check if any item is negativeif any(x < 0 for x in nums):warn()# Filter positive numberspositives = [x for x in nums if x > 0]# Example: Check if any item is negative if any(x < 0 for x in nums): warn() # Filter positive numbers positives = [x for x in nums if x > 0]# Example: Check if any item is negative if any(x < 0 for x in nums): warn() # Filter positive numbers positives = [x for x in nums if x > 0]
Enter fullscreen mode Exit fullscreen mode
Python notes (4 Part Series)
1 Python Notes #1 – General Introduction
2 Python Notes #2 – Data types
3 Python Notes #3 – Control Flow
4 Python Notes #4 – Functions
暂无评论内容