๐ Phase 1: Programming Fundamentals
๐ Topic 4: Python Conditional Statements (if, elif, else)
Welcome back! ๐
In the previous lesson, you learned how to take input from users and display output. Now it's time to learn how Python makes decisions.
Conditional statements allow a program to execute different blocks of code based on whether a condition is True or False.
They are one of the most important concepts in Python and are used extensively in Data Science, Machine Learning, and real-world applications.
๐น 1. What are Conditional Statements?
Conditional statements help Python decide which code should run based on a condition.
Think of it like making everyday decisions:
โข If it's raining โ Carry an umbrella.
โข Else โ Wear sunglasses.
Similarly, Python checks a condition and decides what to execute.
๐น 2. The "if" Statement
The "if" statement executes a block of code only if the condition is True.
Syntax
if condition:
# Code to execute
Example
age = 20
if age >= 18:
print("Eligible to vote")
Output
Eligible to vote
๐น 3. The "if...else" Statement
Use "else" when you want to execute another block if the condition is False.
Example
age = 16
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")
Output
Not eligible to vote
๐น 4. The "if...elif...else" Statement โญ
Use "elif" when you need to check multiple conditions.
Example
marks = 85
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 60:
print("Grade C")
else:
print("Grade D")
Output
Grade B
Python checks conditions from top to bottom and executes the first condition that is True.
๐น 5. Nested "if" Statements
You can place one "if" statement inside another.
Example
age = 25
citizen = True
if age >= 18:
if citizen:
print("Eligible to vote")
Output
Eligible to vote
๐น 6. Using Logical Operators
Conditional statements often use logical operators.
"and"
age = 25
if age >= 18 and age <= 60:
print("Working Age")
"or"
marks = 35
if marks >= 40 or marks == 35:
print("Eligible for Grace Marks")
"not"
is_holiday = False
if not is_holiday:
print("Go to Office")
๐น 7. Checking Multiple Conditions
salary = 60000
experience = 4
if salary > 50000 and experience >= 3:
print("Eligible for Promotion")
else:
print("Not Eligible")
๐น 8. Ternary Operator โญ
A shorter way to write an "if...else" statement.
Syntax
value_if_true if condition else value_if_false
Example
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
Output
Adult
๐น 9. Real-World Example
temperature = 38
if temperature > 35:
print("It's a hot day.")
elif temperature >= 20:
print("Weather is pleasant.")
else:
print("It's cold.")
๐น 10. Common Mistakes
โ Missing Colon
if age >= 18
print("Eligible")
This gives a
SyntaxError.Correct: