Control flow allows your program to branch and take different paths based on specific conditions. In Python, this is handled by if, elif (short for else-if), and else.
1. The Structure
Python relies on indentation to determine which lines of code belong to which branch. A colon : always follows the condition.
2. Comparison Operators
Conditions usually involve comparing values:
==(Equal),!=(Not equal)>(Greater than),<(Less than)>=(Greater or equal),<=(Less or equal)
3. Logical Operators
You can combine multiple conditions using and, or, and not.
# A simple grading system
score = int(input("Enter your test score (0-100): "))
if score >= 90:
print("Grade: A")
print("Excellent work!") # Indented: runs if score >= 90
elif score >= 80:
print("Grade: B")
print("Well done.")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
print("Keep studying, you can do it!")
# One-liner "Ternary" operator
# Syntax: value_if_true if condition else value_if_false
status = "Pass" if score >= 70 else "Fail"
print(f"Final Status: {status}")Key Takeaways
No Parentheses: Unlike C or Java, Python doesn't require
()around the condition, though you can use them for clarity in complex expressions.Elif: You can have as many
elifblocks as you need, but only oneifand oneelse.Indentation Matters: If you forget to indent the code inside a branch, Python will throw an
IndentationError.