Conditional statements in Python allow you to execute certain blocks of code based on specific conditions. The most common conditional statements are if
, else
, and elif
. These statements enable decision-making in a program and are essential for controlling the flow of execution.
if
StatementThe if
statement is used to test a condition. If the condition is true, the block of code inside the if
statement is executed.
# Example 1: Using if statement
x = 10
if x > 5:
print("x is greater than 5")
Output:
x is greater than 5
else
StatementThe else
statement is used to execute a block of code if the if
condition is not true. It is an alternative to the if
statement.
# Example 2: Using else statement
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
elif
StatementThe elif
(else if) statement allows you to check multiple conditions. If the if
condition is false, the program moves to the next condition specified by elif
. You can use multiple elif
statements to check different conditions in a sequence.
# Example 3: Using elif statement
x = 8
if x > 10:
print("x is greater than 10")
elif x == 8:
print("x is equal to 8")
else:
print("x is less than 8")
Output:
x is equal to 8
You can also nest if
, else
, and elif
statements within one another to test more complex conditions.
# Example 4: Nested if statement
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 not greater than 5")
Output:
x is greater than 5 and y is greater than 15
In Python, you can combine multiple conditions using logical operators like and
, or
, and not
within if
, elif
, and else
statements.
# Example 5: Combining conditions with and, or
x = 10
y = 5
if x > 5 and y < 10:
print("x is greater than 5 and y is less than 10")
elif x < 5 or y == 5:
print("x is less than 5 or y is equal to 5")
else:
print("None of the conditions are met")
Output:
x is greater than 5 and y is less than 10
if
Statement with Boolean ValuesIn Python, if
statements work with boolean values as well. The condition in an if
statement is typically a boolean expression that evaluates to either True
or False
.
# Example 6: Boolean condition in if statement
is_raining = True
if is_raining:
print("It is raining. Take an umbrella!")
else:
print("It is not raining. Enjoy your day!")
Output:
It is raining. Take an umbrella!
Python's if
, else
, and elif
statements allow you to implement decision-making in your programs. By using these conditional statements, you can control the flow of your program based on dynamic conditions. Whether you need to handle simple checks or complex logical operations, these statements are essential for writing versatile and functional Python programs.