Control flow is one of the most important aspects of programming. It allows your code to make decisions based on conditions. In Python, this is mainly done using if
, elif
, and else
statements.
These constructs enable your program to execute different blocks of code depending on whether a condition is True
or False
.
How Control Flow Works in Python
if
: Runs a block of code if a condition is true.elif
: Short for "else if", it checks another condition if the previous one was false.else
: Executes a block of code when none of the previous conditions are true.
Example 1: Basic if Statement
age = 20
if age >= 18:
print("You are an adult")
This prints the message because the condition age >= 18
is True
.
Example 2: if-else Statement
temp = 35
if temp > 30:
print("It's hot outside")
else:
print("Weather is pleasant")
If the condition is not met, the else
block is executed.
Example 3: if-elif-else Chain
score = 75
if score >= 90:
print("Grade A")
elif score >= 70:
print("Grade B")
elif score >= 50:
print("Grade C")
else:
print("Fail")
Only the first true condition is executed. This is useful for range checks.
Example 4: Nested if Statements
age = 21
has_id = True
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("ID required")
else:
print("Not allowed")
Nested conditions help when decisions depend on multiple levels of logic.
Example 5: Using Boolean Variables
is_logged_in = False
if not is_logged_in:
print("Please log in")
Boolean flags are often used in control flow for user sessions, feature toggles, etc.
Example 6: Multiple Conditions with and/or
age = 22
has_ticket = True
if age >= 18 and has_ticket:
print("Access granted")
Logical operators like and
and or
can combine multiple checks.
Example 7: Comparing Strings in Conditions
user_input = "yes"
if user_input == "yes":
print("You agreed")
String values are commonly used in user inputs and settings checks.
Example 8: Conditional Expressions (Ternary)
marks = 85
result = "Pass" if marks >= 40 else "Fail"
print(result)
Python allows short if-else expressions in a single line.
Best Practices
- Use indentation consistently (Python uses indentation instead of curly braces).
- Keep conditions readable — use parentheses if needed for clarity.
- Use boolean expressions directly without comparing to
True
orFalse
.
Summary
if
: Checks a condition and executes code if it is true.elif
: Checks another condition if previous ones failed.else
: Executes when none of the above conditions are true.- Logical operators like
and
,or
, andnot
help build complex conditions.
Control flow is what gives your program decision-making ability. Mastering it is essential for building anything from a calculator to a full-fledged web application.