Conditional statements allow a program to execute different blocks of code based on conditions. Python provides if
, if-else
, and if-elif-else
statements to control the flow of execution.
1. The if Statement
Executes a block of code if a condition is True
.
Syntax:
if condition:
# Code block executed if condition is True
Example:
x = 10
if x > 5:
print("x is greater than 5")
Output:
x is greater than 5
2. The if-else Statement
Executes one block of code if the condition is True
, otherwise executes another block.
Syntax:
if condition:
# Code block executed if condition is True
else:
# Code block executed if condition is False
Example:
x = 7
if x % 2 == 0:
print("Even number")
else:
print("Odd number")
Output:
Odd number
3. The if-elif-else Statement
Used to check multiple conditions.
Syntax:
if condition1:
# Code block executed if condition1 is True
elif condition2:
# Code block executed if condition2 is True
else:
# Code block executed if all conditions are False
Example:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Output:
Grade: B
4. Nested if Statements
An if
statement inside another if
statement.
Example:
x = 10
y = 5
if x > 5:
if y > 2:
print("Both conditions are True")
Output:
Both conditions are True
5. Using Logical Operators in Conditions
Python supports logical operators to combine conditions:
and
: ReturnsTrue
if both conditions areTrue
or
: ReturnsTrue
if at least one condition isTrue
not
: Negates a condition
Example:
age = 25
income = 50000
if age > 18 and income > 30000:
print("Eligible for loan")
Output:
Eligible for loan
6. The pass Statement
The pass
statement acts as a placeholder in an if
statement where no code is needed.
Example:
x = 10
if x > 5:
pass # Placeholder for future code
Summary
✅ if statements execute a block of code if a condition is True
.
✅ if-else statements provide an alternative execution path.
✅ if-elif-else statements check multiple conditions.
✅ Nested if statements allow complex decision-making.
✅ Logical operators (and
, or
, not
) help combine conditions.
✅ pass
is used as a placeholder for future code.