
Conditional Statements: if...else
Conditional statements are a cruicial component of Python, enabling programs to execute actions based on specified conditions.
One of the fundamental conditional statements is the if...else
statement, along with its extended form, the if...elif...else
statement. These constructs operate in a manner similar to the use of "if" in human language but utilize Python code to interact with programs. Let's explore some examples below to enhance your understanding of their usage.
Other conditional constructs, such as try, except, and finally
statements, are used for error handling. This more advanced topic will not be discussed in this tutorial.
if...else statement
The example below illustrates the fundamental logic of an if...else
statment in the simplest format.
if True: print('The "if" block ran')else: print('The "else" block ran')
Output:
The "if" block ran
Explanation:
- The
if
keyword is followed by the boolean valueTrue
, which constitutes the condition to be evaluated. - In this case, since the condition is always true, the code within the
if
block will be executed. - Consequently, the program will print
The "if" block ran
. The code in theelse
block will never be executed.
Let's modify the code to execute the else
block.
if False: print('The "if" block ran')else: print('The "else" block ran')
Output:
"else" block ran
Explanation:
- In this scenario, the
if
keyword is followed by the boolean value False, which forms the condition to be evaluated. - The program first proceeds to the
if
statement and evaluate the condition. Since the condition is always false, so the code within theif
block will not be executed. - Instead, the program will proceed to the
else
block and execute the code within it. - Consequently, the program will print
The "else" block ran
.
Now that we've grasped the basic logic of the if...else
statement, let's explore the integration of comparison operations and conditional statements to enahnce their utility.
Example
# Create a variable xx = 20
# Compare the equality of the x variable and 20if x == 20: # If the equality comparison evaluates to True, then execute this code print(x)else: # If the quality comparison evaluates to False, then execute this code print("x doesn't equal to 20")
Output:
20
Explanation:
This code is an example of a if...else
statement that checks the value of a variable x.
- The
if
keyword is followed by a equality comparison:x == 20
. This condition compares the equality beween the variable x and the number 20. - If the condition is true, meaning that x is equal to 20, then the code within the
if
block is executed. In this case, it prints the value ofx
. - If the condition is false, indicating that x is not equal to 20, then the code within the
else
block is executed. This block prints the message "x doesn't equal to 20
". - In this example, the
if
block gets executed and print the value ofx
.
If we set x to 10, the else
block gets executed instead:
# Create a variable xx = 10
# Compare the equality of the x variable and 20if x == 20: # If the equality comparison evaluates to True, then execute this code print(x)else: # If the quality comparison evaluates to False, then execute this code print("x doesn't equal to 20")
Output:
x doesn't equal to 20
After setting x
to 10, the expression x == 20
evaluates to False
, promoting the program to execute the else
block.
Let's see another example.
# Create variables x and yx = 100y = 10
# Compare whether the value of x is less than or equal to the value of yif x <= y: # If the value of x is less than or equal to the value of y, then execute this code print('x <= y')else: # If the value of x is larger than the value of y, then execute this code print('x > y')
Output:
x > y
Explanation:
This code is to compare whether the value of x is less than or equal to the value of y.
- The
if
keyword is followed by a condition:x <= y
. This condition checks if the value of x is less than or equal to the value of y. - If the condition is true, meaning that x is indeed less than or equal to y, then the code within the if block is executed. In this case, it prints the message "
x <= y
". - If the condition is false, indicating that
x
is greater than y, then the code within theelse
block is executed. This block prints the message "x > y
".
For demonstration purposes, the examples above solely utilize the print()
function. It's worth noting that within the if...else
blocks, a variety of actions beyond printing can be executed.
Example
Use if...else
statement to conditionally change the value of a variable.
# Create variables x, y and cx = 100y = 10c = 0
# Compare whether the value of x is less than or equal to the value of yif x <= y: # If the value of x is less than or equal to the value of y, then execute this code c = c + 1else: # If the value of x is larger than the value of y, then execute this code c = c - 1
print("c changes from 0 to", c)
Output:
c changes from 0 to -1
Explanation:
This code sets three variables, x
, y
, and c
, to specific values and then uses an if...else
statement to conditionally change the variable c based on the comparison of x and y.
- The
if
condition checks if the value ofx
is less than or equal to the value ofy
. - If the condition is true, meaning that
y
is indeed less than or equal toy
, then the code within theif
block is executed. In this case, it adds 1 to the value ofc
, effectively incrementing it by 1. - If the condition is false, indicating that
x
is greater thany
, then the code within theelse
block is executed. This block subtracts 1 from the value ofc
, effectively decrementing it by 1.
So, based on the values assigned to x
and y
in this code, it substracts c
by 1 because x (100) is greater than y (10). Therefore, after this code snippet, the value of c becomes -1.
if...elif...else
statement
The if...elif...else
statement expands upon the basic if...else
by adding more conditional layers. You can include multiple elif
statements for additional conditions. Let's explore how this structure operates.
Example
# Create variables x and yx = 100y = 100
# Compare whether x is less than yif x < y: # If x is less than y, then execute this code print('x < y')# Compare whether x is equal to yelif x == y: # If x is euqal to y, then execute this code print('x = y')else: # If x is larger than y, then execute this code print('x > y')
Output:
x = y
In the example, we divide x <= y
to two distinct condtions x < y
and x == y
, enabling the program to respond to different scenarios.
The example below uses both comparison and logical operations in the conditional statements, creating a more complex setup. Can you deduce the conditions covered by the else
statement based on preceeding if
and elif
statements?
Example
# Create variables x and yx = 10y = 10
# Check if both x and y are less than 10.if x < 10 and y < 10: c = x + y# Check if x is less than 10 and y is greater than 10.elif x < 10 and y > 10: c = x * y# Check if x is greater than 10 and y is less than 10.elif x > 10 and y < 10: c = y / x# what condition is included in the else statement?else: c = 0
# Print variable cprint(c)
Output:
0
Explanation:
- The code starts with an
if
statement with the conditionx < 10
andy < 10
. This condition checks if bothx
andy
are less than 10.- If this condition is true, it adds
x
andy
together and assigns the result toc
. In this case,c
becomes 20. - If the condition is false, it moves on to the next
elif (else if)
statement.
- If this condition is true, it adds
- The next
elif
statement has the conditionx < 10
andy > 10
, which checks ifx
is less than 10 andy
is greater than 10.- If this condition is true, it multiplies
x
andy
together and assigns the result toc
. In this case,c
becomes 100. - If the condition is false, it moves on to the next
elif
statement.
- If this condition is true, it multiplies
- The final
elif
statement has the conditionx > 10
andy < 10
, which checks ifx
is greater than 10 andy
is less than 10.- If this condition is true, it divides
y
byx
and assigns the result toc
. In this case,c
becomes 1. - If the condition is false, it falls into the else block.
- If this condition is true, it divides
- The
else
block runs when none of the preceding conditions are met, occurring when bothx
andy
are greater than or equal to 10. In this scenario, it setsc
to 0.
Recap
Conditional statements are a powerful tool that enable programs to operate differently under various conditions. We'll explore more use cases as we delve into additional topics in Python.