Chapter 8: if-conditions
Default and boolean operators in Python
In the introductory chapters, you have already learned some of Python’s default operators. Here is a list of useful mathematical operators:
Operator | Description |
---|---|
+ , - , * , / |
addition, subtraction, multiplication, division |
// |
integer division |
% |
modulo (“rest” of a division) |
-x , +x |
sign |
** |
exponentiation |
Another class of operators are boolean (logical) operators:
Operator | Description |
---|---|
< , > , <= , >= |
comparison operators is smaller/equal? bigger/equal? |
== |
comparison operator is equal? |
!= |
comparison operator is not equal? |
or , and , not |
boolean comparison operators |
in |
is element of? |
Examples:
print(f"2 < 5? {2 < 5}")
print(f"3 > 7? {3 > 7}")
x = 11
print(f"x > 10? {x > 10}")
print(f"2 * x < x? {2 * x < x}")
print(f"type of 'True': {type(True)}")
2 < 5? True
3 > 7? False
x > 10? True
2 * x < x? False
type of 'True': <class 'bool'>
The boolean expressions True
and False
can be used as any other common value in Python:
my_variable = True
print(f"type of my_variable: {type(my_variable)}")
type of my_variable: <class 'bool'>
if-conditions
We can further extend the usage of boolean comparison operators when it comes to decision making in your code, e.g., when you want to execute a certain code line (or lines) only if a certain condition is satisfied. For such decision making, the concept of if-statements is provided:
if condition1:
action 1
elif condition2:
action 2
else:
action 3
We can use the previously introduced logical comparison operators to test a condition:
Equals: a == b, a in b
Not Equals: a != b, a not b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
For example:
""" Change the value of a and b randomly and run this and the
subsequent cell:
"""
a=7
b=3
if a==b:
print('check: a and b are equal')
else:
print('failed: a and b are not equal')
failed: a and b are not equal
if a>b:
print('check: a is greater than b')
else:
print('failed: a is not greater than b')
check: a is greater than b
You can also combine several conditions:
if a>b:
print('a is greater than b')
elif a<b:
print('a is lower than b')
elif a==b:
print('a and b are equal')
a is greater than b
Also, you can concatenate several conditions by combining two conditions with the comparison operators and
or or
:
if (condition1) and/or (condition 2):
action 1
elif (condition3) and/or (condition 4):
action 2
For example:
# Change the value of c randomly and run this cell:
c=11
if (a>b) and (a<c):
print('a is in the interval between b and c')
else:
if a>b:
print('a is in not between b and c, ')
print(' but greater than b')
elif a<c:
print('a is in not between b and c, ')
print(' but lower than c')
else:
print('a is in not between b and c, ')
a is in the interval between b and c
Note: As for for-loops, Python relies on indentation (whitespace at the beginning of a line) to define the scope of a code block in your code
Exercise 1
Write a script, that uses the following code line in order to set the value number_of_moves
:
number_of_moves = int(input("How many times have you moved in your life?? "))
Write an if-statement, that checks the input number_of_moves
and gives out the following responses:
- “You’re quite a globetrotter.”, if
number_of_moves
is greater than 9. - “You have come around a lot.”, if
number_of_moves
is greater than 7 and less than or equal 9. - “Your moving rate corresponds to the national average.”, if
number_of_moves
is greater than 3 and less than or equal 7. - “You are a settled person.”, if the
number_of_moves
is less than or equal 3.
Execute your code several time and change your input number.
# Your solution here:
How many times have you moved in your life?? 5
Your moving rate corresponds to the national average!
Toggle solution
The boolean operator in
There are also boolean operators that are applied to types others than numbers. A useful Boolean operator is in
, checking membership in a sequence:
# with a number list:
number_list = [3, 4, 0, 5, 2, 99, 4]
check_number=1
if check_number in number_list:
print(f"{check_number} is in number_list")
else:
print(f"{check_number} is not in number_list")
1 is not in number_list
# with a word list:
word_list = ['Toto', 'Harry', 'Mickey']
check_word= "Harry"
if check_word in word_list:
print(f"{check_word} is member of word_list")
else:
print(f"{check_word} is not member of word_list")
Harry is member of word_list
I.e., with the in
-operator you can easily check, e.g., whether a certain string is part another string-sequence.
Combine if-statement with a for-loop
Of course we can combine if-statements with a for-loop (and vice versa):
Exercise 2
Given the list agents=["James Bond (007)", "Austin Powers (007)", "Hubert Bonisseur, (117)"]
, write a for-loop, that iterates over each of its elements and checks, if the current agent has a 007-license.
# Your solution here:
match! James Bond (007) has a 007 license.
match! Austin Powers (007) has a 007 license.
warning! Hubert Bonisseur, (117) has no 007 license!
Toggle solution
Exercise 3
- Create a
new_number_list
ranging from 0 to 22 (use thelist()
andrange()
commands). - Write a for-loop, that iterates over each element of
new_number_list
. - Within the for-loop, set up an if-condition, that prints out the current
new_umber_list
-element, if its value is higher than 10, otherwise print out “value below threshold”. - Change the threshold to any other number between 0 and 22 and re-run your script.
# Your solution here:
0 is below the threshold 10!
1 is below the threshold 10!
2 is below the threshold 10!
3 is below the threshold 10!
4 is below the threshold 10!
5 is below the threshold 10!
6 is below the threshold 10!
7 is below the threshold 10!
8 is below the threshold 10!
9 is below the threshold 10!
10 is below the threshold 10!
match! 11 is greater than 10.
match! 12 is greater than 10.
match! 13 is greater than 10.
match! 14 is greater than 10.
match! 15 is greater than 10.
match! 16 is greater than 10.
match! 17 is greater than 10.
match! 18 is greater than 10.
match! 19 is greater than 10.
match! 20 is greater than 10.
match! 21 is greater than 10.
Toggle solution
Combine if-statement with a list comprehension
Please read in the for-loop chapter about list comprehension.
Before we combine an if-statement with a for-loop within a list comprehension, let’s approach this goal stepwise:
my_list=[4, 8, 12, 16, 20, 32, 28, 24, -1, 32, 32]
number_to_check = 12
# list comprehension with for-loop (pre-step, just to understand,
# what's going on):
#print([i for i, val in enumerate(my_list)] )
#print([val for i, val in enumerate(my_list)] )
print([(i, val) for i, val in enumerate(my_list)] )
[(0, 4), (1, 8), (2, 12), (3, 16), (4, 20), (5, 32), (6, 28), (7, 24), (8, -1), (9, 32), (10, 32)]
# list comprehension with for-loop and if-statement:
print([(i, val) for i, val in enumerate(my_list) #artificial line break
if val==number_to_check])
[(2, 12)]
# vs. conventional for-loop and if-statements:
for i, val in enumerate(my_list):
if val == number_to_check:
print(i, val)
2 12
Note: We have introduced the linebreak within a command definition via “" + enter into the new line. Most Python IDE will then auto-indent the new line to some extend. For the code itself, it is not necessary to add a linebreak - it just makes the code userfriendly readable (if necessary).