Understanding Conditional Statements in Python (if, elif, else)
Introduction
Every program needs to make decisions. For example — checking whether a user entered the correct password or whether a number is positive or negative.
In Python, we use conditional statements (if, elif, else) to make such decisions.
1. The if Statement
The if statement checks a condition — if it’s True, the code inside the block runs.
Example:
x = 10
if x > 5:
    print("x is greater than 5")
Output:
x is greater than 5
 2. The if-else Statement
Sometimes, you want one thing to happen when the condition is true and another when it’s false.
Example:
x = 3
if x % 2 == 0:
    print("Even number")
else:
    print("Odd number")
Output:
Odd number
 3. The if-elif-else Ladder
When you need to check multiple conditions, use elif (short for “else if”).
Example:
marks = 85
if marks >= 90:
    print("Grade A")
elif marks >= 75:
    print("Grade B")
elif marks >= 50:
    print("Grade C")
else:
    print("Fail")
Output:
Grade B
 4. Nested if Statements
You can also use one if statement inside another.
Example:
num = 12
if num > 0:
    if num % 2 == 0:
        print("Positive and Even")
Output:
Positive and Even
5. Real-Life Example
Here’s a small program that decides if a person is eligible to vote.
Example:
age = int(input("Enter your age: "))
if age >= 18:
    print("You are eligible to vote.")
else:
    print("Sorry, you are not eligible to vote.")
Output:
You are eligible to vote.
Quick Tips
- 
Always indent your Python code properly under if,elif, orelse.
- 
Conditions must evaluate to True or False. 
- 
Use and,or, andnotfor combining multiple conditions.
Example:
if age > 18 and country == "India":
    print("Eligible voter")
Challenge for You
Write a Python program that asks the user for a number and prints:
- 
“Positive” if it’s greater than 0 
- 
“Negative” if less than 0 
- 
“Zero” otherwise 
Final Thoughts
Conditional statements are the foundation of logic building in programming.
Practice them well, because they form the core of decision making in every program.
Comments
Post a Comment