Conditional Statements
[Link] Statement:
Definition
The if statement checks a condition — if it’s True, the block of code inside if runs.
If it’s False, Python skips it.
Syntax
if condition:
# code to execute if condition is true
Example 1
age = 20
if age >= 18:
print("You are eligible to vote.")
Output:
You are eligible to vote.
Example 2
num = 5
if num > 0:
print("Positive number")
Output:
Positive number
[Link]-else Statement:
Definition
Used when we want to do one thing if the condition is true,
and something else if it’s false.
Syntax
if condition:
# runs if condition is true
else:
# runs if condition is false
Example 1
age = 16
if age >= 18:
print("Adult")
else:
print("Minor")
Output:
Minor
Example 2
num = -3
if num >= 0:
print("Positive")
else:
print("Negative")
Output:
Negative
[Link] Statement (Else If):
Definition
When you have multiple conditions, use elif.
Only the first true condition block runs.
Syntax
if condition1:
# code
elif condition2:
# code
else:
# code
Example 1
marks = 85
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 60:
print("Grade C")
else:
print("Fail")
Output:
Grade B
[Link] Conditions:
Definition
You can put an if statement inside another if or else block.
This is called nesting — used when multiple related conditions must be checked.
Syntax
if condition1:
if condition2:
# code if both true
else:
# code if inner condition false
else:
# outer else
Example 1
age = 20
if age >= 18:
if age >= 60:
print("Senior Citizen")
else:
print("Adult")
else:
print("Minor")
Output:
Adult
Example 2
num = 15
if num > 0:
if num % 2 == 0:
print("Positive Even")
else:
print("Positive Odd")
else:
print("Negative number")
Output:
Positive Odd
[Link] Operator (Conditional Expression)
Definition
A one-line shorthand for if-else.
It returns one value if the condition is true, and another if it’s false.
Syntax
value_if_true if condition else value_if_false
Example 1
age = 18
status = "Adult" if age >= 18 else "Minor"
print(status)
Output:
Adult
PRACTICE PROGRAMS
Program 1: Grade Calculation
Example
marks = int(input("Enter your marks: "))
if marks >= 90:
grade = "A"
elif marks >= 75:
grade = "B"
elif marks >= 60:
grade = "C"
elif marks >= 50:
grade = "D"
else:
grade = "Fail"
print("Your Grade is:", grade)
Output:
Enter your marks: 82
Your Grade is: B
Program 2: Largest of Three Numbers
Example
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
if a > b and a > c:
print("Largest number is:", a)
elif b > c:
print("Largest number is:", b)
else:
print("Largest number is:", c)
Output:
Enter first number: 10
Enter second number: 25
Enter third number: 20
Largest number is: 25