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

To fulfill your request, we can modify the provided code to include a try-except statement and a while loop. This will ensure that the program continues to prompt the user until a valid input is entered. Below is the modified code:

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  # Ask for input again
        break  # Exit loop if input is valid
    except ValueError:
        print("Invalid input. Please enter a numeric value.")

Explanation:

  1. While Loop: The loop will continue indefinitely until it encounters a break statement.
  2. Try-Except Block:
    • The try block attempts to convert the input into an integer.
    • If a ValueError occurs (for instance, if the input is not an integer), it will catch the error, print a message, and prompt for input again.
  3. Fee Calculation: The fee is calculated based on the number of hours parked, and if the input is valid and positive, it exits the loop with break.

You can copy this code into PythonAnywhere, run it, and share the link as requested. If you need any further assistance or modifications, feel free to ask!