8.3k views
0 votes
You are to write a mall program to read in 2 numbers for hour and minute of a 24-hour time. Then, convert it into 12-hour time. You need to define an exception class called TimeFormatMistake. If the user enters an illegal time like 10:65, your program will throw and catch a TimeFormatMistake.

Read Programming Project 1 of chapter 16, page 894 for more information.

Below is a sample dialogue. The boldface is user's input.

Enter time in 24-hour format:

Hour: 13

Minute: 7

That is 1:07 PM

Again (y/n)? y

Enter time in 24-hour format:

Hour: 10

Minute: 15

That is 10:15 AM

Again (y/n)? y

Enter time in 24-hour format:

Hour: 10

Minute: 65

There is no such time as 10:65

Again (y/n)? y

Enter time in 24-hour format:

Hour: 32

Minute: 30

There is no such time as 32:30

Again (y/n)? y

Enter time in 24-hour format:

Hour: 16

Minute: 5

That is 4:05 PM

Again (y/n)? n

Good-bye

User Sambua
by
9.3k points

1 Answer

1 vote

Here is a program that fulfills the requirements:

class TimeFormatMistake(Exception):

pass

while True:

try:

hour = int(input("Hour: "))

minute = int(input("Minute: "))

if hour > 23 or minute > 59:

raise TimeFormatMistake

if hour == 0 or hour == 12:

hour_str = "12"

elif hour < 12:

hour_str = str(hour)

else:

hour_str = str(hour-12)

if minute < 10:

minute_str = "0" + str(minute)

else:

minute_str = str(minute)

print(f"That is {hour_str}:{minute_str} { 'AM' if hour < 12 else 'PM'}")

except TimeFormatMistake:

print("There is no such time as {}:{} ".format(hour, minute))

again = input("Again (y/n)? ")

if again.lower() != 'y':

print("Good-bye")

break

User KennyBartMan
by
8.4k points

No related questions found