x = True
type(x)bool
As our programs become more complex, we will often need to run a block of code only if a specific condition is met. For example, we might want to output a message only if a certain number is less than some specified value. This is where conditions come in handy – they allow us to run code only if a condition is fulfilled. Conditions are another important building block of almost any real-world program. Just like functions, conditions allow us to control the flow of execution.
A condition is based on a comparison. A comparison is an expression, which means that it has a value. Because a condition can only be either true or false, Python has a special data type bool exactly for this purpose. Therefore, a bool can either be True or False (notice the capitalization of the first letters):
x = True
type(x)bool
y = False
type(y)bool
Python has the following binary comparison operators:
==!=<><=>=Here are some examples:
x = 2
x == 2True
Mixing up the equality operator == with the assignment operator = is a common mistake, so make sure to use the correct operator in your code!
x != 2False
x > 2False
x < 10True
We can combine two or more comparisons using the and and or keywords:
x > 0 and x < 10True
x == -2 or x == 2True
x > 5 or x < 10 and x > 8False
Python has a shortcut for checking if a number is within a certain range. Instead of writing:
x > 0 and x < 10True
We can write:
0 < x < 10True
The not keyword inverts a boolean expression:
not TrueFalse
not FalseTrue
not 0 < x < 10False
We can always use parentheses to change precedence or improve readability:
not (0 < x < 10)False
(x < 0) or (x >= 2)True
Python also has an exclusive or (XOR) operator ^, which returns True if exactly one of the two operands is True:
True ^ FalseTrue
True ^ TrueFalse
Python distinguishes between integer numbers (int) and floating point numbers (float). These two types represent numbers differently. Most noteably, int numbers have exact internal representations, whereas float numbers can only be stored with limited precision. This can lead to subtle issues, especially when comparing two floating point numbers for equality:
0.1 + 0.1 + 0.1 == 0.3False
A common solution is to allow a certain amount of “wiggle space” in the comparison:
(0.1 + 0.1 + 0.1) - 0.3 < 1e-15True
The math module has a function called isclose, which can be used exactly for this purpose:
import math
math.isclose(0.1 + 0.1 + 0.1, 0.3)True
Python supports expressing decimal numbers using scientific notation with powers of ten. It uses the symbol e, which can be read as “times ten to the power of”. The following examples illustrate this concept:
1e0 # 1 times 10 to the power of 01.0
-4e0 # -4 times 10 to the power of 0-4.0
1e1 # 1 times 10 to the power of 110.0
3.5e2 # 3.5 times 10 to the power of 2350.0
1e-2 # 1 times 10 to the power of -20.01
1e-15 # 1 times 10 to the power of -15 = 0.0000000000000011e-15
Note that the result is always a regular float number.
We are now ready to discuss conditions. A condition checks whether a specific comparison (boolean expression) is True or False. Python runs an associated block of code only if the result is True.
Here’s the structure of a condition in pseudo-code:
if <expression is True>:
<do something>
...
...
elif <expression is True>: # optional
<do something else>
...
elif <expression is True>: # optional
<do something else>
...
...
else: # optional
<do something>
The indented lines of code belonging to a specific condition are only executed if the corresponding condition is True. We can test several conditions sequentially by using elif statements after the initial if statement. If no condition is True, Python runs the code in the else block.
Importantly, Python only executes the first block of code where the condition returns True. If this happens, all other elif and else blocks are skipped.
Let’s work through some examples. Here’s a simple condition consisting of only one if statement:
a = 2
if a > 0:
print("a is a positive number")
print("this is good to know")a is a positive number
this is good to know
If we run these lines, Python will execute the indented lines of code, because a is in fact greater than zero. Since the condition a > 0 is True, we get the two lines of output.
If we take the same if block, but set a = 0 before, we do not get any output, because Python does not run the two lines (the condition a > 0 is False):
a = 0
if a > 0:
print("a is a positive number")
print("this is good to know")We can add an optional else branch, which Python runs if none of the previous conditions evaluated to True:
a = 0
if a > 0:
print("a is a positive number")
print("this is good to know")
else:
print("a is either 0 or a negative number")a is either 0 or a negative number
Now because a > 0 is False, Python will run the code associated with the else branch.
Also optionally, we can add (an arbitrary number of) elif branches, for example:
a = -5
if a > 0:
print("a is a positive number")
print("this is good to know")
elif a < 0:
print("a is a negative number")
else:
print("a is 0")a is a negative number
Due to the fact that Python only runs the code associated with the first condition yielding True, the order of conditions is important. Consider the following two examples containing identical conditions, but in a different order:
a = 4
if a > 5:
print("One")
elif a < 10:
print("Two")
elif a == 4:
print("Three")
else:
print("Four")Two
Now we swap the order of the two elif branches:
a = 4
if a > 5:
print("One")
elif a == 4:
print("Three")
elif a < 10:
print("Two")
else:
print("Four")This example demonstrates that the order of branches is important.
We haven’t really talked about data types other than numeric ones yet, but Python can also compare non-numeric types such as strings:
p = "Python"
r = "R"
p == rFalse
p > rFalse
p < rTrue
Therefore, we can use such comparisons in a condition:
if p != r:
print("Python and R are different, but both are pretty cool!")Python and R are different, but both are pretty cool!
Write the following program:
x and y. You can use the input function to get user input. Note that input always returns a str, but you can use the int function to convert a number contained in a str to int!x and y, check if their sum is greater than 50.Write a function is_odd, which has one parameter x and returns True if x is odd. If x is even, the function returns False. Note that you can check if a number is odd if dividing this number by 2 has a remainder of 1 (for even numbers, the remainder is 0). Use the % operator to compute the remainder!
Convert the following nested conditions into one block with if/elif/else branches:
if x > 0:
print("x is positive")
else:
if x < 0:
print("x is negative")
else:
print("x is equal to 0")
This document is licensed under the CC BY-NC-SA 4.0 by Clemens Brunner.