(python) Using Modulo To Get The Remainder From Changing Secs, To Hrs And Minutes
I'm currently new to learning python and stumbled upon this problem: Exercise 2-7 Get the Time Write an algorithm that reads the amount of time in seconds and then displays the
Solution 1:
This is just "out of my head", because I got no testing system I could use right now.
def amount_time(t):
print("Number of Seconds:", t % 60)
print("Number of Minutes:", (t // 60) % 60)print("Number of Hours:", (t // 3600))
What "t % 60" does:
- take t, divide it by 60
- remove everthing left of the dot
- multiply with 60
With numbers:
- 5000 / 60 = 83.33333
- => 0.33333
- 0.33333 * 60 = 20
Solution 2:
Your calculation of minuts doesnt work correct, you use Modulo with the hours. You could do the same with minutes as you did wirh seconds instead:
m = (t - h * 3600) // 60s = int (t - h*3600 - m*60)
ms = int ((t - h*3600 - m*60 - s) * 1000) # milliseconds
and to build the result string there are better ways, f.e.
print'{}:{}:{}.{}'.format(h,m,s,ms)
You find more ways and options to Format, if you look here:
Post a Comment for "(python) Using Modulo To Get The Remainder From Changing Secs, To Hrs And Minutes"