4 Conditional execution
Warning
Any changes you make to the code on this page, including your solutions to exercises, are temporary. If you leave or reload the page, all changes will be lost. If you would like to keep your work, copy and paste your code into a separate file or editor where it can be saved permanently.
4.1 Comparison operators
Comparison operators let us check how two values relate to each other. They work with many types of data, including numbers, strings, and lists. Every comparison produces either True or False, the only two values of the bool type. In Python (unlike in some other languages), True and False are capitalized.
We have already seen the == operator, which checks if two values are equal. To check if two values are not equal, we use !=:
Values being compared do not need to have the same type:
Note that the integer 1 is equal to the floating-point number 1.0 (this particular float can be represented exactly). But the integer 1 is not equal to the string ‘1’.
The ordering operators <, <=, >, and >= let us compare values by their order:
When comparing strings, Python uses alphabetical order. Lists are compared in a similar way, element by element. This is called lexicographical order:
An expression whose result is a boolean value (True or False) is called a boolean expression. All of the examples above are boolean expressions. We can also create more complex ones using variables, constants, comparison operators, logical operators such as and, or, and not, and parentheses to group parts together:
4.2 Conditional execution
The if statement lets us run part of a program (a code block) only when a certain condition is met. A condition is usually a boolean expression (something that evaluates to True or False).
if condition:
# Code block to be executed if the `condition` is TrueIn Python, we show which lines belong to a block by adding spaces at the beginning of each line. This is called indentation. All statements in the block must
- start with the same number of spaces, and
- be indented more than the
ifline itself.
The Python style guide recommends to use 4 spaces.
if condition:
do_something()
do_something_else()
do_something_afterwards()Here, do_something() and do_something_else() each start with 4 spaces, so they belong to the if block. These lines are executed only if the condition is True. If the condition is False, they are skipped. The last line, do_something_afterwards(), has the same indentation as the if line, so it is outside the block. It always run, no matter whether the condition is True or False.
A code block must contain at least one statement. If you do not want to add any code yet, you can use the pass statement, which does nothing but keeps the block syntactically correct:
if condition:
pass # We will add the code laterExample. The following program asks the user to input a positive integer and displays a message if the entered value is not positive:
Exercise. Run the cell above multiple times and enter both positive and non-positive values. Use the explain feature to visualize the program’s execution steps.
We can also add an else block, which contains the statements that are executed if the if condition is not met:
if condition:
# Executed if the `condition` is True
else:
# Executed if the `condition` is FalseSometimes we want to check multiple conditions in sequence. This is done using elif (short for “else if”) along with an optional else at the end:
if condition_1:
# Executed if the `condition_1` is True.
elif condition_2:
# Executed if the `condition_1` is False, and the `condition_2` is True
elif condition_3:
# Executed if the `condition_1` and the `condition_2` are both False, and the `condition_3` is True
else:
# Executed if all conditions are FalseIt is also possible to nest conditionals, meaning you can place an if inside another if block:
if condition_1:
# Executed if the `condition 1` is True
if condition_2:
# Executed if both the `condition_1` and the `condition_2` are True
else:
# Executed if the `condition_1` is True, but the `condition_2` is False
# Executed if the `condition 1` is True
else:
# Executed if the `condition 1` is FalseExample. The following program asks the user to enter an integer and tells them whether it is negative, positive or zero. Run the program multiple times to see the results for different inputs.
Example. This program demonstrates a nested conditional. It checks whether an entered number falls between 1 and 10. Run the program multiple times and input values such as -10, 5, 25, or even non-numeric input (like ‘Python’) to see how it behaves.
Exercise. Modify the code in the last program so that it shows the message “It is not between 1 and 10.” if the number falls outside the specified range.
Solution
# Option 1:
# x = int(input("Enter an integer number: "))
# print("You entered:", x)
# if x >= 1:
# if x <= 10:
# print("It is between 1 and 10.")
# else:
# print("It is not between 1 and 10.")
# else:
# print("It is not between 1 and 10.")
# Option 2:
# If we do not want to repeat `print("It is not between 1 and 10.")`
x = int(input("Enter an integer number: "))
print("You entered:", x)
is_between = False
if x >= 1:
if x <= 10:
is_between = True
print("It is between 1 and 10.")
if not is_between:
print("It is not between 1 and 10.")Exercise. Rewrite the program to use only one if statement.
Sample solution
x = int(input("Enter an integer number: "))
print("You entered:", x)
if x >= 1 and x <= 10: # Can be simplified to: if 1 <= x <= 10:
print("It is between 1 and 10.")
else:
print("It is not between 1 and 10.")