5. Flow control#
Exercise 5.1.#
Create a variable named hour and asign it a value in between 0 and 23. Assuming that this variable represents a given time, print a message that is appropriate for the part of the day this hour is in. If the variable hour has value 10, for instance, the code should print 'Good morning!' and if hour has value 23, the code should print 'Good night!'
hour = 21
print( f"It is now {hour} o'clock" )
# We check for two conditions at once using `and`
if hour > 6 and hour < 12:
print("Good morning!")
elif hour < 17:
print("Good afternoon!")
elif hour < 23:
print("Good evening!")
else:
print("Good night!")
Note that we expect the value of hour to be reasonable for our code to work as expected.
For example, we don’t check whether hour is at least 0 or at most 23.
It is advisable to include these checks in code that you rely on.
In case you wondered if you can make the comparisons more compact, you can! You can compare a number to two numbers at the same time, as demonstrated below.
Exercise 5.2.#
Strings can be viewed as collections of characters. When you iterate across a string using a for loop, you will receive each individual character in sequence. Try to write code which prints each character of the string on a separate line.
text = 'Flow control'
for t in text:
print(t)
Exercise 5.3.#
The list named years brings together a number of years. Use the keywords for and if to select the years from this list that are in the 18th century. Remember that you can combine multiple Boolean expressions using and.
years = [ 1756, 1575, 2002, 1984 ,1626 ,1791, 1714, 1873, 1991 ]
# Print years that are in the 18th century
for year in years:
if year > 1700 and year < 1800:
print( f'{year} is in the 18th century.')
1756 is in the 18th century.
1791 is in the 18th century.
1714 is in the 18th century.
Exercise 5.4.#
Building on the code you developed for exercise 4.2, try to write code which can reverse the order of the characters in a given string.
You can test your code with the following examples:
Input |
Output |
|---|---|
time |
emit |
drawer |
reward |
stressed |
desserts |
Start by defining an empty output string, as follows.
output_string = ''
Next, iterate across all the individual characters of the string and append the output string to the right of this character.
input_string = 'drawer'
output_string = ''
for character in input_string:
output_string = character + output_string
print(output_string)
reward
Exercise 5.5.#
We have two lists of numbers and would like to know which numbers in the first list are not in the second list. Write code which can extract those numbers from the first list that are not in the second list.
first = [4, 9, 1, 17, 11, 26, 28, 54, 63]
second = [8, 9, 74, 21, 45, 11, 63, 28, 26]
numbers_not_in_second = []
# Add the numbers from `first` that are not in `second` to `numbers_not_in_second`
for f in first:
if f not in second:
numbers_not_in_second.append(f)
print(numbers_not_in_second)
[4, 1, 17, 54]
Exercise 5.6.#
We have a list of websites and are interested to find the Dutch ones.
Write some code to select the Dutch websites from this list. Tip: You may want to reuse some of the code developed for exercise 3.4.
websites = [
'https://www.universiteitleiden.nl',
'https://www.stanford.edu',
'https://www.uu.nl',
'http://www.ox.ac.uk',
'https://www.rug.nl',
'https://www.hu-berlin.de',
'https://www.uva.nl'
]
# Print the URLs that belong to Dutch institutions
for url in websites:
# Extract the top-level domain, i.e. everything after the final dot
# You can leave out the end index of the 'slice' to get everything until the end of the string
top_level_domain = url[ url.rindex('.') + 1 : ]
# Dutch institutions have a '.nl' website
if top_level_domain == 'nl':
print(url)
Exercise 5.7.#
Program a small guessing game. In this game, the player needs to guess a number in between 1 and 50. You can use the code below as a basis.
The randint() method from random can be used, firstly, to generate a random integer.
Use the function input() to request a value from the user. The function int() needs to be used to convert the input into an integer.
When the user enters a value which is too low or too high, this information is communicated to the user via a print statement. To test whether the number that is guesses is correct, you can work with the equality (==) and the inequality (!=) operators.
Hint: you will need to combine the different kinds of flow control to complete the whole game. Start by checking if the guessed number is correct and making sure that this part of the code works as you expect. When that works, think which parts of the code need to be repeated to let the player guess until the number was found.
from random import randint
max_number = 50
number_to_guess = randint(0,max_number)
guess = int( input( f"Guess a number in between 1 and {max_number}: ") )
while guess != number_to_guess:
if guess > number_to_guess:
print("Lower!")
elif guess < number_to_guess: # this could be 'else:'
print("Higher!")
guess = int( input("Guess again ... \n") )
print( f"The correct number is indeed {number_to_guess}." )