Conditional statements in Python let your program make decisions based on conditions. The main keywords are if, elif, and else.
if runs a block when the condition is true.elif lets you check more conditions if the previous ones are false.else runs a block when all previous conditions are false.if statements to handle more complex decisions.True or False.if–elif–else chain runs.if statement inside another if for detailed checks.Basic if syntax:
if condition:
# block of code
statement1
statement2
if–else syntax:
if condition:
# block if condition is True
statement1
else:
# block if condition is False
statement2
if–elif–else chain syntax:
if condition1:
# runs if condition1 is True
statement_block_1
elif condition2:
# runs if condition2 is True
statement_block_2
elif condition3:
# runs if condition3 is True
statement_block_3
else:
# runs if all conditions above are False
default_statement_block
Nested if syntax:
if outer_condition:
# outer block
if inner_condition:
# inner block
statement_block_inner
else:
statement_block_inner_else
else:
statement_block_outer_else
The if statement allows you to execute a block of code only if a condition is true.
age = 18
# Check if the person is an adult
if age >= 18:
print("You are an adult.")
In this example, the message is printed only if the condition age >= 18 is true.
The else clause allows you to execute a block of code if the if condition is false.
age = 16
# Decide if the person is an adult or a minor
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
The elif statement allows you to check multiple conditions in sequence.
score = 85
# Choose the grade based on the score
if score >= 90:
print("Grade A")
elif score >= 75:
print("Grade B")
else:
print("Grade C")
Here, Python checks the if condition first. If false, it checks elif, and finally else if all conditions are false.
You can also nest if statements inside another if statement for more complex conditions.
num = 15
# Check if the number is positive and whether it is even or odd
if num > 0:
if num % 2 == 0:
print("Positive Even Number")
else:
print("Positive Odd Number")
else:
print("Non-positive Number")
age >= 18 is True, so it prints:You are an adult.age >= 18 is False, so the else block runs and prints:You are a minor.score >= 90 is False, second condition score >= 75 is True, so it prints:Grade Bnum > 0 is True, so we go inside:
num % 2 == 0 is False, so the inner else runs and prints:Positive Odd Numberif for simple conditional checks.elif for multiple conditions instead of writing many separate if blocks.if statements for complex logic that depends on previous checks.if-elif-else.if to check if a number is even and positive.