I need to write a really simple python program to solve this issue. I have most of the program written but, when I run the second example, the result is incorrect. Examples 1 and 3 work just fine.

Write a program to calculate the number of seconds since midnight. For example, suppose the time is 1:02:05 AM. Since there are 3600 seconds per hour and 60 seconds per minutes, it has been 3725 seconds since midnight (3600 * 1 + 2 * 60 + 5 = 3725). The program asks the user to enter 4 pieces of information: hour, minute, second, and AM/PM. The program will calculate and display the number of seconds since midnight. [Hint: be very careful when the hour is 12].

Examples for testing code:

Enter hour: 1 Enter minute: 2 Enter second: 5 Enter AM or PM: AM Seconds since midnight: 3725

Enter hour: 11 Enter minute: 58 Enter second: 59 Enter AM or PM: PM Seconds since midnight: 86339

Enter hour: 12 Enter minute: 7 Enter second: 20 Enter AM or PM: AM Seconds since midnight: 440

Here is the code that I have written: As I have said, It should be a simple program.

Thank you in advance for your help!!!!


hour = float(input("Enter hour:"))
minute = float(input("Enter minute:"))
second = float(input("Enter second:"))
am_pm = input ("Enter AM or PM:")
if am_pm == "am" and hour == 12:
hour = 0
seconds_since_midnight = ((3600 * hour) +(minute *60) + second)
print("Seconds since midnight:", seconds_since_midnight)

Respuesta :

Answer:

hour = float(input("Enter hour:"))

minute = float(input("Enter minute:"))

second = float(input("Enter second:"))

am_pm = input ("Enter AM or PM:")

if am_pm == "AM":

   if hour == 12:

       hour = 0

   seconds_since_midnight = ((3600 * hour) +(minute *60) + second)

elif am_pm == "PM":

   seconds_since_midnight = ((3600 * (hour+12)) +(minute *60) + second)

print("Seconds since midnight:", int(seconds_since_midnight))

Explanation:

The point here is when PM is chosen, you need to add 12 to the hour. I added elif  part to satisfy this. Moreover, since the output is in integer format, you may need to apply type casting for seconds_since_midnight variable.