Python Essentials: From First Commands to Custom Functions - Part 2
This is Part 2 of the series. Read Part 1 first.
In the journey of becoming a professional developer—whether you're aiming for Django backend development, AI automation, or Data Science—the goal isn't just to write code that works. The goal is to write code that is Pythonic: short, readable, elegant, and clear.
This guide dives into the logic of conditionals, the efficiency of Pythonic expressions, and the structural power of the new match statement.
1. Logic and Conditionals: Making Decisions
Conditionals are the brain of your script. They allow your code to choose between different paths based on specific situations.
The Toolkit: Conditional Operators
To compare values, Python uses a standard set of operators:
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
< / > | Less than / Greater than |
<= / >= | Less than or equal / Greater than or equal |
Choosing Your Structure: if vs. if-elif-else
A common "real-life bug" occurs when developers use multiple if statements instead of an if-elif chain.
The "Asking 3 Teachers" Problem (Multiple ifs):
If you use only if statements, Python checks every single one, even if the first one was already true.
marks = 85
if marks >= 50: print("Pass") # ✅ Prints
if marks >= 70: print("Good") # ✅ Prints
if marks >= 80: print("Excellent") # ✅ Prints
# Result: Three separate messages for one grade.
The "Decisive Teacher" Solution (if-elif):
In an if-elif chain, Python stops as soon as it finds the first True condition. Order matters here: always check the strictest or highest condition first.
marks = 85
if marks >= 80:
print("Excellent") # ✅ Prints and STOPS.
elif marks >= 70:
print("Good")
else:
print("Fail")
Logical Alternatives: or vs. and
orOperator: ReturnsTrueif at least one condition is true. Perfect for checking alternatives (e.g.,if role == "admin" or role == "editor").andOperator: ReturnsTrueonly if both conditions are true. Use this for specific ranges (e.g., checking if a number falls between 10 and 20).
2. The Art of Pythonic Expressions
"Pythonic" code uses built-in features to avoid unnecessary variables and repetitive logic. It looks natural, almost like reading English.
Comparison: ❌ Non-Pythonic vs. ✅ Pythonic
| Goal | ❌ Non-Pythonic | ✅ Pythonic |
|---|---|---|
| Booleans | if is_active == True: | if is_active: |
| Empty Lists | if len(my_list) == 0: | if not my_list: |
| Multiple ORs | if r == "admin" or r == "editor": | if r in ["admin", "editor"]: |
| Swap Variables | temp = a; a = b; b = temp | a, b = b, a |
| One-Line If | if age >= 18: s = "Adult" | status = "Adult" if age >= 18 else "Minor" |
Functions and Implicit Returns
Instead of writing a full if-else inside a function to return a Boolean, remember that a comparison is already an expression that evaluates to True or False.
# ❌ Instead of this:
def even(n):
if n % 2 == 0: return True
else: return False
# ✅ Do this:
def even(n):
return n % 2 == 0
3. Structural Pattern Matching: The match Statement
Introduced in Python 3.10, match is the cleaner, more powerful sibling of if-elif. While if-elif is like asking many yes/no questions, match is like picking a specific option from a menu.
When to use match
Use it when comparing one variable against many fixed patterns, such as API Request Handling (GET, POST, PUT, DELETE) or Command Line Tools.
command = input("Enter command: ")
match command:
case "start":
print("Starting service...")
case "stop":
print("Stopping service...")
case "restart" | "reload": # Using | as 'or'
print("Restarting...")
case _: # The "Default" case (if nothing matches)
print("Unknown command")
Advanced Power: Unlike switch statements in other languages, Python's match can "unpack" data. For example, case ("login", username): can extract the username directly from a tuple.
4. Professional Standards: The "Bug-Free" Checklist
In Python, indentation and the colon (:) are not optional—they are compulsory parts of the syntax. As you write, always ask yourself:
- Readability: Can someone else understand this in 5 seconds?
- Efficiency: Can I get the computer to ask fewer questions (e.g., using
eliformatchinstead of multipleifs)? - Bugs: Am I checking for the right Boolean values (
True/Falsewith capital letters)?
Previous in the Series
👈 Python Essentials: From First Commands to Custom Functions - Part 1 — Covers terminal basics, data types, string formatting, and writing clean functions.
Share this post