Conditional Statements in Python
Conditional statements allow a program to execute different code blocks based on conditions. Python provides three primary types of conditional statements:
ifStatementif-elseStatementif-elif-elseStatement
These are used to control the flow of a program based on different conditions.
1. if Statement
The if statement checks a condition and executes the indented block only if the condition evaluates to True.
Syntax:
if condition:
# Code to execute if the condition is True
Example: Checking if a number is positive
num = 10
if num > 0:
print("The number is positive")
Output:
The number is positive
πΉ How It Works:
- The condition
num > 0is evaluated. - If it is
True, Python executes the indented statement (print()in this case). - If it is
False, the block is skipped.
Example: Greeting a User
name = input("Enter Name:")
if name == "Alice":
print("Hello Alice, Good Morning")
print("How are you!!!")
If the user enters "Alice", the program prints "Hello Alice, Good Morning". Otherwise, it only prints "How are you!!!".
2. if-else Statement
The if-else statement is used when we need to execute one block of code if a condition is True and a different block if the condition is False.
Syntax:
if condition:
# Block executed if condition is True
else:
# Block executed if condition is False
Example: Checking Even or Odd Number
num = 7
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
Output:
Odd number
Example: Greeting Based on User Input
name = input("Enter Name:")
if name == "Alice":
print("Hello Alice, Good Morning")
else:
print("Hello Guest, Good Morning")
print("How are you!!!")
If the user enters "Alice", the program prints "Hello Alice, Good Morning". Otherwise, it prints "Hello Guest, Good Morning".
3. if-elif-else Statement
Sometimes, we need to check multiple conditions. The if-elif-else statement is used to handle such scenarios.
Syntax:
if condition1:
# Executes if condition1 is True
elif condition2:
# Executes if condition2 is True
elif condition3:
# Executes if condition3 is True
else:
# Executes if none of the conditions are True
Example: Assigning Grades Based on Marks
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
Example: Choosing a Favorite Brand
brand = input("Enter Your Favourite Brand:")
if brand == "RC":
print("It is a children's brand")
elif brand == "KF":
print("It is not that much kick")
elif brand == "FO":
print("Buy one, get one free")
else:
print("Other brands are not recommended")
If the user enters "KF", the output will be:
It is not that much kick
4. Short-Hand if-else (Ternary Operator)
Python allows a shorter way to write if-else using a ternary operator.
Syntax:
value_if_true if condition else value_if_false
Example: Checking Voting Eligibility
age = 20
status = "Eligible to vote" if age >= 18 else "Not eligible to vote"
print(status)
Output:
Eligible to vote
5. Nested if Statements
We can place an if statement inside another if statement, known as nesting.
Example: Checking if a Number is Positive and Even
num = 10
if num > 0:
print("The number is positive")
if num % 2 == 0:
print("It is an even number")
Output:
The number is positive
It is an even number
Example: Checking the Largest of Three Numbers
n1 = int(input("Enter First Number:"))
n2 = int(input("Enter Second Number:"))
n3 = int(input("Enter Third Number:"))
if n1 > n2 and n1 > n3:
print("Biggest Number is:", n1)
elif n2 > n3:
print("Biggest Number is:", n2)
else:
print("Biggest Number is:", n3)
If the user enters 10, 20, 30, the output will be:
Biggest Number is: 30
This example shows how multiple if-elif conditions help in decision-making.
6. Important Notes on Conditional Statements
✅ Python Does Not Have a switch Statement
Unlike other programming languages, Python does not provide a switch-case statement. Instead, if-elif-else statements serve the same purpose.
✅ else is Optional
An if statement does not always require an else. If no condition matches and else is absent, nothing happens.
✅ Python Uses Indentation Instead of Braces {}
Python uses whitespace (indentation) to define blocks instead of {} used in languages like C, Java.
❌ Incorrect:
if age >= 18:
print("Eligible to vote") # Incorrect because it's not indented properly
✅ Correct:
if age >= 18:
print("Eligible to vote") # Correct indentation
Conclusion
- Conditional statements (
if,if-else,if-elif-else) help control the flow of execution. - The
ifstatement checks a condition and executes a block ifTrue. - The
if-elsestatement provides an alternative when the condition isFalse. - The
if-elif-elsestructure helps when multiple conditions need to be checked. - Python also supports short-hand
if-else(ternary operator) and nestedifstatements.