Write a program that reads in a time of the form hour:minute, validates the inpu
ID: 3564741 • Letter: W
Question
Write a program that reads in a time of the form hour:minute, validates the input and prints the time in the form hh:mm AM or hh:mm PM. You may assume that hour and minute are numbers. The input is in military time: that is, it goes from 0 hour to 23 hours.
Your program must check for invalid conditions such as negative hour or minute, wrong values such as 24 for the hour value or 60 for minutes.
The program works as follows:
Enter time: 9:5
09:05 AM
Enter time: 0:-7
Minute should not be less than 0
Enter time: 12:59
12:59 PM
Enter time: 13:00
01:00 PM
Explanation / Answer
Program:
# Get value from the user
val = raw_input('Enter time (Hour:Minute):')
# Split the value into hour and minute
values = val.split(":")
# Convert the hour into integer
hour = int(values[0])
# Convert the minute into integer
minute = int(values[1])
# Check whether the hour is valid or not
if (hour < 0 or hour > 23):
print("Invalid hour")
# Check whether the minute is valid or not
if(minute > 59 or minute < 0):
print("Invalid minute")
# Check whether the time is AM or PM
if(hour >= 12 and minute > 0):
day = "PM"
else:
day = "AM"
# Compute railway time
if(day == "PM" and hour > 12):
hour = hour - 12
# Print the hours
print(hour, ":", minute, " ", day)
-----------------------------------------------------------------------------------------
Output:
Enter time (Hour:Minute): 1:56
01:56 AM
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.