Assignment #03

Unit 3

Learning by quizzing

A fun way to deepen and extend what you’ve learned so far is to try the following quizzes. You may encounter questions on topics we haven’t fully covered yet—feel free to skip those.

If you find the questions on a specific topic too hard, take the corresponding tutorial in the left sidebar on https://www.w3schools.com/python/.

Exercises

Do the exercises embedded in the lecture material that we didn’t do in class and the ones below.

#03-03: Classification

Write a Python program that classifies energy consumption based on the user’s input. Ask the user to enter the daily energy consumption in kilowatt-hours (kWh), and then categorize it into one of the following categories:

  • “Low Consumption” for consumption less than 8 kWh
  • “Moderate Consumption” for consumption between 8 kWh and 15 kWh
  • “High Consumption” for consumption greater than 15 kWh

Once the above program runs, think about how to make the program more robust. What happens if the user responds with a word, such as ‘ten’? Modify the program, so that it displays a meaningful message that tells the user that the input could not be processed and that the program expects an integer or float as input. After this message, the program should exit without a classification result.

#03-04: Hello, conditional execution

Write a program that prompts a user for their name and preferred language, and then welcomes them. The output should look like

Enter your name: Florian
Enter your language (EN, DE, XX): EN
How's it, Florian!

The allowed languages are English, German, and a third language of your choice. If the language is not one of these three options, the program should print an error message and exit without a welcome message.

Solutions

# Note that this solution implements a TypeError (instead of a simple print message), 
# which we briefly got to know later in that session

consumption = input('Enter Consumption in kWh: ')

try:  
    consumption = float(consumption)
except:
    raise TypeError("My personal error message!")
    
if consumption < 8:
    print('Low Consumption')
elif consumption >= 8 and consumption < 15:
    print('Moderate Consumption')
else:
    print('High Consumption')
# Prompt the user for their name and preferred language
name = input("Enter your name: ")
language = input("Enter your language (EN, DE, FR): ")

if language == "EN":
    print("How's it, " + name + "!")
elif language == "DE":
    print("Hallo, " + name + "!")
elif language == "FR":
    print("Bonjour, " + name + "!")
else:
    print("Unsupported language. Please choose EN, DE, or FR.")