Conditional statements are one of the basic tools in programming for controlling information flow and decision making. Python provides a set of built-in statements that allow dynamic interactions with data, allowing the program to adapt to a variety of situations.
The ‘if’ statement
The ‘if’ statement allows you to execute a block of code only if the specified condition is true.
if <condition>:
<block of code>
...
Example:
x = 10
if x > 5:
print("x is greater than 5")
Result of the above code:
x is greater than 5
In this example, the text ‘x is greater than 5‘ is displayed because the condition ‘x > 5‘ is true.
The ‘else’ statement
The ‘else‘ statement allows you to execute a block of code if the condition in the ‘if‘ statement is false.
if <condition>:
<block of code>
...
else:
<block of code>
...
Example:
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
Result of the above code:
x is less than or equal to 5
In this example, the text ‘x is less than or equal to 5‘ is displayed because the condition ‘x > 5‘ is false.
The ‘elif’ statement
The ‘elif‘ statement is used in conjunction with ‘if‘ and ‘else‘ to create more complex conditional structures. It acts as an additional condition that is only checked if the condition in the ‘if‘ is false. This allows multiple conditions to be checked one after the other.
if <condition>:
<block of code>
...
elif <condition>:
<block of code>
...
elif <condition>:
<block of code>
...
...
else:
<block of code>
...
Example:
x = 10
if x > 15:
print("x is greater than 15")
elif x > 10:
print("x is greater than 10 but less than or equal to 15")
elif x > 5:
print("x is greater than 5, but less than or equal to 10")
else:
print("x is less than or equal to 5")
Result of the above code:
x is greater than 5, but less than or equal to 10
In this example, the code sequentially checks three conditions (x > 15, x > 10, x > 5) and uses two ‘elif‘ statements to handle additional cases. If none of the conditions are true, the block of code in ‘else‘ is executed.
The ‘pass’ statement
The ‘pass’ statement is a so-called empty statement that does nothing. It can be used as a placeholder where the code must be syntactically correct, but does not perform any action.
if <condition>:
pass