Python Conditional Statements: Comparison Operators and Control Flow
Conditional statements allow your Python programs to make decisions. In this guide, you’ll learn how to use if
, elif
, and else
with comparison operators to control program flow. Includes examples and practice exercises.
Comparison Operators
These operators return True
or False
to evaluate conditions:
==
: Equal to!=
: Not equal to>
: Greater than<
: Less than>=
: Greater than or equal to<=
: Less than or equal to
# Example: Check if a number is positive
num = 10
if num > 0:
print("Positive number")
Conditional Statements (if, elif, else)
Basic if Statement
disk_usage = 85
if disk_usage > 80:
print("Warning: Disk usage is above 80%")
if-elif-else Chain
status_code = 404
if status_code == 200:
print("OK")
elif status_code == 404:
print("Not found")
else:
print("Error")
Nested Conditionals
user_logged_in = True
user_role = 'admin'
if user_logged_in:
if user_role == 'admin':
print("Access granted to admin panel")
else:
print("Login required")
Even/Odd Check
number = int(input("Enter a number: "))
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
Practice Work
Exercise 1: Fix the Code
Identify and correct errors in this conditional statement:
temperature = 32
if temperature =< 0: print("Freezing") elif temperature > 0 or temperature < 30:
print("Cold")
eles:
print("Hot")
temperature = 32
if temperature <= 0:
print("Freezing")
elif 0 < temperature < 30:
print("Cold")
else:
print("Hot")
Exercise 2: User Authentication
Write a program that checks if:
- Username is “admin”
- Password is “secret123”
# Your code here
username = input("Enter username: ")
password = input("Enter password: ")
if username == "admin" and password == "secret123":
print("Access granted")
else:
print("Invalid credentials")
Exercise 3: Grade Classifier
Convert a numerical score (0-100) to a letter grade:
- A: 90-100
- B: 80-89
- C: 70-79
- F: Below 70
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("F")
Workshop: Real-World Scenarios
Workshop 1: Discount Calculator
Apply discounts based on purchase amount:
- $100+ : 10% off
- $200+ : 20% off
- $500+ : 30% off
amount = float(input("Enter purchase amount: $"))
# Your code here
Workshop 2: Leap Year Checker
A year is a leap year if:
- Divisible by 4, but not by 100
- Unless also divisible by 400
year = 2024
# Your code here
Best Practices
- Avoid Deep Nesting: Use
elif
instead of multiple nestedif
statements. - Use Parentheses for Complex Conditions:
(x > 5) and (y < 10)
- Write Readable Conditions: Use variables like
is_logged_in
instead ofuser == True
.
Conclusion
Conditional statements are the backbone of decision-making in Python. Master comparison operators and practice with real-world scenarios to write efficient, readable code.
Next: Explore Python Loops and Logical Operators.