In this lab, you will be given an example of some code in PythonAnywhere, to which you need to add a try-except statement, based on the error that arises.  Watch the video below for a couple of examples of what you will be doing here as well as some help with the example for your assignment.Now, follow the PythonAnywhere starter link below, copy to your account, add a try-except statement and while loop to ensure the program created will run a loop until the appropriate input has been entered. Once you are done, click the share button and copy the link into the answer space below.

hours = int(input("Please enter the number of hours parked: "))
if hours > 24:
print("Your fee is ", hours * 2.5)
if hours > 18:
print("Your fee is ", hours * 3)
if hours > 12:
print("Your fee is ", hours * 3.5)
if hours > 6:
print("Your fee is ", hours * 4)
if hours > 0:
print("Your fee is ", hours * 5)
else:
print("The hour must be positive.")

1 answer

Here's an improved version of the code that includes a try-except statement and a while loop to ensure the user inputs a valid number of hours. The loop will continue until a valid input is provided.

while True:
    try:
        hours = int(input("Please enter the number of hours parked: "))
        if hours > 24:
            print("Your fee is ", hours * 2.5)
        elif hours > 18:
            print("Your fee is ", hours * 3)
        elif hours > 12:
            print("Your fee is ", hours * 3.5)
        elif hours > 6:
            print("Your fee is ", hours * 4)
        elif hours > 0:
            print("Your fee is ", hours * 5)
        else:
            print("The hour must be positive.")
            continue  # To loop again for positive hours
        break  # Exit the loop if input is valid
    except ValueError:
        print("Invalid input. Please enter a valid integer.")

In this code:

  • A while True loop is used to repeatedly prompt the user until valid input is given.
  • A try block attempts to convert the input to an integer.
  • If the conversion fails, a ValueError is caught, and an appropriate message is displayed.
  • If an invalid number of hours (i.e., less than or equal to 0) is entered, the program prints an error message and continues the loop without breaking out.
  • The program breaks the loop and stops prompting once valid input is provided.