Chapter: Conditional Statements in Python – if
, elif
, and else
π Introduction
Conditional statements in Python are used to perform different actions based on different conditions. The most commonly used are:
if
(for a single condition)elif
(for multiple conditions)else
(for the default action)
These help you make decisions in your codeβjust like we do in real life!
π§ Why Use Conditional Statements?
Imagine you’re writing a program to decide if someone can vote:
- If the person is 18 or older β allow voting
- Otherwise β not allowed to vote
This is exactly where if-else
comes into play.
πΉ Syntax of if
Statement
if condition:
# code block (runs only if condition is True)
β Example:
age = 20
if age >= 18:
print("You are eligible to vote.")
π Output:
You are eligible to vote.
πΈ Adding else
for an Alternate Path
if condition:
# if condition is True
else:
# if condition is False
β Example:
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
π Output:
You are not eligible to vote.
πΈ Using elif
for Multiple Conditions
if condition1:
# if condition1 is True
elif condition2:
# if condition2 is True
else:
# if none of the above are True
β Example:
marks = 75
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: F")
π Output:
Grade: B
π‘ Nested if
Statements
You can place one if
inside another if
.
β Example:
age = 25
citizen = True
if age >= 18:
if citizen:
print("Eligible to vote.")
else:
print("Not a citizen, cannot vote.")
else:
print("Too young to vote.")
π Output:
Eligible to vote.
π§ͺ Practice Exercises
- Even or Odd Checker
- Take an integer input and print whether it’s even or odd.
- Temperature Message
- If temp > 30 β “It’s hot”
- If temp between 20-30 β “Nice weather”
- Else β “It’s cold”
- Login System
- Check if the username and password match and print “Login successful”, otherwise print “Invalid credentials”.
β Quick Tips
- Conditions use comparison operators:
==
,!=
,<
,>
,<=
,>=
- Indentation is mandatory after
if
,elif
, andelse
(usually 4 spaces) - Python evaluates conditions top-down, so order matters in
elif
chains
π§Ύ Summary
Keyword | Purpose |
---|---|
if | Tests a condition |
elif | Tests another condition if previous are False |
else | Default block if none match |
π§βπ» Mini Project: Simple Grading System
score = int(input("Enter your score: "))
if score >= 90:
print("Grade A")
elif score >= 75:
print("Grade B")
elif score >= 60:
print("Grade C")
else:
print("Grade F")