Module 11 of 13 · Text
LAB
LAB
Objectives
- improving the ability to use numbers, operators, and arithmetic operations in Python
- using the print() function's formatting capabilities
- learning to express everyday-life phenomena in terms of programming language
Scenario
Your task is to prepare a simple code able to evaluate the end time of a period of time, given as a number of minutes (it could be arbitrarily large). The start time is given as a pair of hours (0..23) and minutes (0..59). The result has to be printed to the console.
For example, if an event starts at 12:17 and lasts 59 minutes, it will end at 13:16.
Don't worry about any imperfections in your code - it's okay if it accepts the invalid time - the most important thing is that the code produce valid results for valid input dat.
Test Data
Sample input:
12
17
59
Expected output: 13:16
Sample input:
23
58
642
Expected output: 10:40
Sample input:
0
1
2939
Expected output: 1:0
Used ChatGPT for code:
start_hour = int(input("Enter the starting hour (0-23): "))
start_minute = int(input("Enter the starting minute (0-59): "))
duration_minutes = int(input("Enter the duration in minutes: "))
start_total_minutes = start_hour * 60 + start_minute
end_total_minutes = (start_total_minutes + duration_minutes) % 1440
end_hour = end_total_minutes // 60
end_minute = end_total_minutes % 60
print("End time: {:02d}:{:02d}".format(end_hour, end_minute))
Explanation:
- The input() function is used to prompt the user for the starting hour, starting minute, and duration in minutes.
- The start_total_minutes variable is calculated by converting the starting hour to minutes and adding it to the starting minute.
- The end_total_minutes variable is calculated by adding the start_total_minutes and the duration_minutes, and then taking the modulo 1440 (the number of minutes in a day) to handle cases where the end time is on the next day.
- The end_hour and end_minute variables are calculated by converting the end_total_minutes to hours and minutes, respectively, using integer division and modulo.
- Finally, the end time is printed in the format hh:mm, with leading zeros added if necessary using the {:02d} format specifier.