Conditions in Python: if, elif and else
In programming, it is often necessary for the code to only be executed when certain conditions are met. In Python, you can define these conditions using the keywords if
, elif
(short for "else if") and else
.
Table of Contents
- Conditions in Python: if, elif and else
- if Statement
- if-elif-else Statement
- Combining Conditions with Logical Operators
- Nested if Statements
if Statement
The if
statement in Python is used to execute an action when a condition is true. Here’s an example:
x = 15
if x > 10:
print("x is greater than 10")
In this example, the output "x is greater than 10" will only be printed if the condition x > 10
is true.
if-elif-else Statement
You can also combine multiple conditions by using a series of if
, elif
and else
statements. The elif
statement is only executed if the preceding condition is false. Here’s an example:
x = 10
if x < 5:
print("x is less than 5")
elif x > 10:
print("x is greater than 10")
else:
print("x is 5 or 10 or between")
In this example, the output "x is greater than 10" will only be printed if x > 10
is true. If x < 5
is false and x > 10
is false, then the last condition (else
) will be evaluated and the output "x is 5 or 10 or between" will be printed.
Combining Conditions with Logical Operators
You can also use logical operators like and
, or
and not
to combine multiple conditions. Here’s an example:
x = 10
y = 5
if x > 5 and y < 10:
print("x is greater than 5 and y is less than 10")
In this example, the output will only be printed if both conditions x > 5
and y < 10
are true.
Nested if Statements
You can also nest if
statements inside other if
statements to define more complex conditions. Here’s an example:
x = 10
y = 5
if x > 5:
if y < 10:
print("x is greater than 5 and y is less than 10")
else:
print("x is greater than 5, but y is greater than or equal to 10")
else:
print("x is less than or equal to 5")
In this example, the inner if
statement will only be executed if the outer condition x > 5
is true. If y < 10
is true, then the output "x is greater than 5 and y is less than 10" will be printed. Otherwise, the output "x is greater than 5, but y is greater than or equal to 10" will be printed.