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.