Conditional statements in Python allow decisions to be made in a program based on conditions.
Indentation (usually 4 spaces) is very important: it tells Python which code belongs to which block
(if, else, etc.). This document explains all conditional statements with definition, use, syntax,
examples, tips, and summary.
1. if Statement
Definition: Executes a block of code only if the condition is True.
Use: To check a single condition. Useful when there’s only one path to follow if the condition holds.
Syntax:
if condition:
# code to execute
Example 1:
x = 10
if x > 5:
print("x is greater than 5")
Output:
x is greater than 5
Example 2:
temperature = 30
if temperature > 25:
print("It’s a hot day")
Output:
It’s a hot day
Real-Life Example (Age Check for Voting):
age = 20
if age >= 18:
print("Eligible to vote")
Output:
Eligible to vote
Tip: Use `if` when you don’t need an alternative option.
2. if-else Statement
Definition: Executes one block if the condition is True, otherwise another block.
Use: To handle two-way decisions. Example: pass/fail, yes/no, valid/invalid.
Syntax:
if condition:
# code if condition is true
else:
# code if condition is false
Example 1:
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
Output:
x is not greater than 5
Example 2:
num = -4
if num >= 0:
print("Positive number")
else:
print("Negative number")