Write a program that asks the user for an hour between 1 and 12, asks them to enter am or pm, and asks them how many hours into the future they want to go. Print out what the hour willbe that many hours into the future, printing am or pm as appropriate. An example is shown below.Enter hour: 8 am (1) or pm (2)? 1 How many hours ahead? 5 New hour: 1 pm.
hour = int(input("Enter hour: "))
am_pm = int(input("am (1) or pm (2)? "))
num_hours_ahead = int(input("How many hours ahead? "))
if am_pm == 1:
am_pm_str = "am"
else:
am_pm_str = "pm"
new_hour = (hour + num_hours_ahead) % 12
if new_hour == 0:
new_hour = 12
if new_hour < hour:
if am_pm_str == "am":
am_pm_str = "pm"
else:
am_pm_str = "am"
print(f"New hour: {new_hour} {am_pm_str}")This program first prompts the user for an hour, the "am" or "pm" indicator, and the number of hours into the future they want to go. It then converts the "am" or "pm" indicator to a string and calculates the new hour by adding the number of hours ahead to the original hour and taking the modulus 12. If the new hour is 0, it sets it to 12. If the new hour is less than the original hour, it changes the "am" or "pm" indicator accordingly. Finally, it prints the new hour and the "am" or "pm" indicator.
You could name this program "time_calculator" or something similar.
Here is an example of the output of the program I provided:
Enter hour: 8
am (1) or pm (2)? 1
How many hours ahead? 5
New hour: 1 pm
This is what the user would see if they entered 8, 1, and 5 when prompted for the hour, the "am" or "pm" indicator, and the number of hours into the future they want to go. The new hour would be calculated as (8 + 5) % 12 = 1, and the "am" or "pm" indicator would be "pm" because the new hour is less than the original hour.
Here is another example of the output:
Enter hour: 12
am (1) or pm (2)? 2
How many hours ahead? 3
New hour: 3 pm
In this example, the user entered 12, 2, and 3 when prompted for the input values. The new hour would be calculated as (12 + 3) % 12 = 3, and the "am" or "pm" indicator would be "pm" because the original indicator was "pm".
Note that the output will vary depending on the input values. The program will calculate the new hour and the "am" or "pm" indicator based on the input values and print them.
0 Comments