The if-else
statement is a fundamental control structure that allows you to execute certain code blocks based on specific conditions. Here’s a detailed breakdown of how it works:
if-else
SyntaxThe basic syntax for an if-else
statement is as follows:
if condition:
# block of code executed if the condition is true
else:
# block of code executed if the condition is false
if condition:
: This line checks if the condition
evaluates to True
. If it does, the indented block of code following the if
statement is executed.else:
: If the condition
in the if
statement evaluates to False
, the code block following the else
statement is executed instead.x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
Output:
x is greater than 5
elif
ClauseYou can use the elif
(short for “else if”) clause to check multiple conditions sequentially. The elif
clause comes after the if
statement and before the else
statement, if present. Here’s the syntax:
if condition1:
# block of code executed if condition1 is true
elif condition2:
# block of code executed if condition2 is true
else:
# block of code executed if both condition1 and condition2 are false
x = 15
if x > 20:
print("x is greater than 20")
elif x > 10:
print("x is greater than 10 but not greater than 20")
else:
print("x is 10 or less")
Output:
x is greater than 10 but not greater than 20
if
StatementsYou can nest if
statements within each other to create more complex conditional logic.
x = 10
y = 20
if x > 5:
if y > 15:
print("x is greater than 5 and y is greater than 15")
else:
print("x is greater than 5 but y is not greater than 15")
else:
print("x is 5 or less")
Output:
x is greater than 5 and y is greater than 15
You can use logical operators (and
, or
, not
) to combine multiple conditions within an if
statement.
x = 10
y = 20
if x > 5 and y > 15:
print("x is greater than 5 and y is greater than 15")
else:
print("One or both conditions are not met")
Output:
x is greater than 5 and y is greater than 15
if
statement checks a condition and executes the associated block if the condition is True
.else
statement executes a block of code if the if
condition is False
.elif
statement allows you to check multiple conditions in sequence.if
statements and use logical operators to create more complex conditions.