Homework for Week 2
After this week you can
- Use different kinds of branching to execute or skip a part of the code
- Combine conditional statements into more complex conditional structures
- Use try-except to handle runtime errors
- Add the correct amount of indentation into the statements
Conditional execution
Conditional statements allow the computer to execute parts of code conditionally: depending on whether some condition is true or false, a block of commands is executed or skipped. Typical conditions are comparisons, which check, for example, whether one value is less or greater than another. In Python, there are different forms of conditional statements used in different situations, and they can be flexibly combined with each other.
Watch the videos about how Python executes some statements and skips others:
Slides in English
Textbook in English
Quiz
Go to Moodle and solve the second quiz about the video lectures.
- Quiz can be solved several times.
- Best attempt counts.
Examples
This week we are into if-else and try-except statements. These constructs (and others that we'll learn in the future) can be mixed with each other: for example, we can write a program that asks for an input, checks if it is valid, and, depending on the value entered, chooses what to output.
Age group
Write a program that gets the age of the user and prints into what age group the user belongs to. The program must work correctly even if the user enters something else than a number for the age.
age_as_string = input("How old are you? ") try: # Try to convert the input to an integer age = int(age_as_string) except: # Conversion failed, let age be -1 in this case age = -1 if age < 0: print("This is not a valid age") elif age < 18: print("You are a minor") elif age < 100: print("You are an adult") else: print("Wow, you need a lot of birthday candles!")
Here, try and except are used to test the user input for validity. If the age cannot be converted to an integer, then the program sets the age equal to -1. Therefore, in the following, it may assume that the variable age always has a numeric value and process it with the ordinary if - elif - else statements.
Number comparison
Write a program that prompts the user for two integers and then displays a message saying which of them is greater.
try: x = int(input('Enter the first number: ')) y = int(input('Enter the second number: ')) except: print('Please enter a number') else: # If both int coversions were successful, then continue here if x == y: print('Numbers are equal') else: if x < y: print(x, 'is less than', y) else: print(x, 'is greater than', y)
If the conversion to integer fails, then the program prints a message and terminates. Note the else part of the try-except block. That will be executed when the conversion succeeds.
Exercises
Python documentation
Study the Python documentation about the "math" module (http://docs.python.org/3/library/math.html). Find the meanings of floor and ceil commands – you may need them when solving the following exercises. Also, review the documentation about string methods (http://docs.python.org/3/library/stdtypes.html#string-methods).
Square brackets in the documentation mean that it is not necessary to give value to that parameter when calling the function because the parameter has a default value. For example, if the description of the method is str.center(width[, fillchar]), then this means that it can be used either with one argument, like client_name.center(80), or with two arguments, like client_name.center(80, '~').
1. Speeding fine
When the maximum driving speed is exceeded, a fine is imposed. The size of the fine is obtained by multiplying the number of km/h's above the allowed limit by 3. The maximum fine is 190 euros.
Write a program that
- prompts the user for the name, speed limit, and actual speed;
- calculates the fine according to the rules above;
- outputs the name and the size of the fine on the screen.
Example
Enter name: Jürgen
Enter speed limit (km/h): 60
Enter actual speed (km/h): 80
Jürgen, your fine for speeding is €60.
Explanation: the speed limit is exceeded by 80 − 60 = 20 km/h. Therefore, the fine is 3 · 20 = 60 euros.
Second example
Enter name: Hendrik
Enter speed limit (km/h): 50
Enter actual speed (km/h): 172
Hendrik, your fine for speeding is €190.
Explanation: the speed is exceeded by 172 − 50 = 122 km/h. The calculation gives a fine of 3 · 122 = 366 euros. Since it exceeds the maximum amount of the fine, the actual fine will be 190 euros.
2. Name of the month
Write a program that asks the user to enter a month number and then prints the name of the month.
If the user enters an integer outside the range 1...12, then the programs should print a message informing about that. You can assume that the user enters only integers.
Test your program with different inputs.
Examples
Enter month number: 2
February
Enter month number: 0
Month number must be in the range [1-12]
Enter month number: 13
The year has only 12 months
3. Painting the walls
Mikk is renovating his apartment and wants to paint all the walls in his bathroom. In the store, wall paint is sold in cans of a fixed size. One liter of paint can cover 8 square meters. Write a program that asks for the length, width, and height of the room (in meters) and the volume of paint in one can (in liters) and outputs how many cans of paint he needs to buy to paint the walls.
Assume that the bathroom has no windows and that the door will also be painted the same color. The ceiling and floor are not painted. All input data are floating point numbers.
Example 1
Enter room length: 3.5
Enter room width: 2.8
Enter room height: 2.5
Enter volume of one can: 0.9
You have to buy 5 cans of paint.
Example 2
Enter room length: 3
Enter room width: 2
Enter room height: 2.4
Enter volume of one can: 2.7
You have to buy 2 cans of paint.
Submit your solutions
Submit your solutions of exercises 1, 2, and 3 to the autotester in Moodle, under Homework for Week 2.
NB! Use home1.py, home2.py, and home3.py as the names of your files.
Advice
Start early. For example, flight training students are instructed to take off at the beginning of the runway because that part of the runway you have left behind will be of no more use to you.