Assignment 11 - ldkvd/CS101L GitHub Wiki
Welcome to the CS101L Wiki!
Clock Program
We’ll use our skills to create a clock class that can keep track of hours, minutes, and seconds. Then you should be able to create an instance with values for hours, minutes, and seconds. You’ll want to make a new class with a ini method. You’ll want to set the attributes for an hour, minute, and second in the init.
Create a string override method so that the hour, minute, seconds output with a nice 24-hour format style. It should output as 02:10:15 for the example above. In order to output leading zeros, you can use .format like below
Create a tick() method for the clock. When a tick gets called, it should increment the # of seconds. If the number of seconds is 60 or over, then then we increment the number of minutes and set seconds to 0. If the number of minutes gets set to 60 or over, then we increment the hours.
We’ll want to add a new default argument to the init method which will be the clock type. The parameter will default to 0, which means a 24-hour clock. The other option 1 would indicate a 12-hour clock. The internal clock will remain unchanged, but our output when printed will change depending on what type of clock is represented. The 12-hour clock will only show hours 1 -12, with am or pm. 00:00:20 would be 12:00:20 am. While 12:00:20 would be 12:00:20 pm
Using the clock class we’ve built create a program to ask a user for hours, minutes and seconds, and create a clock based on that. Then write a loop that calls tick() once a second and then sleeps for a second. Use the time module to sleep.
Answers:
The image above is code 1/3.
The image above is code 2/3.
The image above is code 3/3.
The image above is the output.
In this program, a class called House was created. The constructor had parameters of hour, minute, second, and clock type. The default clock type was set to 0. A string method was created to override the constructor and display the time. If-statements are used to identify whether to display the 24-hour format or the 12-hour format clock. A tick method was defined to increment the number of hours, minutes, and/or seconds. If statements were used to identify whether to increment seconds, minutes, hours, or all as well as set certain variables to 0 depending on the appropriate situation. In the main, the program asked the user to input hour, minute, and time. An object of the class clock was created and called in a while loop. This allows for the clock to run and display continuously.