CONDITIONAL STATEMENTS
Conditional statements in Python are used to execute different code blocks based on certain conditions. The main conditional statements in Python are if
, elif
(short for else if), and else
. Here's how they work:
1. if
statement:
The if
statement checks a condition and executes a block of code if the condition is true.
x = 10
if x > 5:
print("x is greater than 5")
2. if``else
statement:
The else
statement is used in conjunction with if
to execute a block of code when the if
condition is false.
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
3. if``elif``else
statement:
The elif
statement allows you to check additional conditions if the previous conditions are false.
x = 10
if x > 15:
print("x is greater than 15")
elif x > 5:
print("x is greater than 5 but not greater than 15")
else:
print("x is not greater than 15 or 5")
You can also nest conditional statements within each other to create more complex logic:
x = 10
y = 20
if x > 5:
if y > 10:
print("x is greater than 5 and y is greater than 10")
else:
print("x is greater than 5 but y is not greater than 10")
else:
print("x is not greater than 5")
It's important to maintain proper indentation in Python because it signifies the blocks of code that belong together. The standard convention is to use four spaces for each level of indentation.