1

I understand how I would type this in IDLE, but I don't really understand the math behind it. Specifically lines 8 and 11... Can someone walk me through this, so I can understand the basic math that's going on here?

# Get a number of seconds from the user.
total_seconds = float(input('Enter a number of seconds: '))

# Get the number of hours.
hours = total_seconds // 3600

# Get the number of remaining minutes.
minutes = (total_seconds // 60) % 60

# Get the number of remaining seconds.
seconds = total_seconds % 60

# Display the results.
print('Here is the time in hours, minutes, and seconds:')
print('Hours:', hours)
print('Minutes:', minutes)
print('Seconds:', seconds)
  • Say, if I was to enter 11730 seconds, I know i would get back 3.0 hours, 15.0 minutes, and 30.0 seconds. What math is going on that would result in that answer, though? – delta_stream Aug 27 '20 at 18:57

1 Answers1

2

You seem to be confused about the modulo operator. See also the docs and / or this question / post for more details.

In short, the modulo operator divides and returns the remainder of the division or 0 in case there is no remainder.

Lets look at your example step by step:

>>> total_seconds = 11730
>>> total_seconds / 3600
3.2583333333333333

So you have 3 hours and the decimal part specifies minutes and seconds.

>>> total_seconds / 60 
195.5

You already know that you have 3 full hours thus you can remove it

>>> (total_seconds / 60) - 3 * 60
15.5

which is the same as

>>> (total_seconds / 60) % 60
15.5

So you got 3 hours, 15 minutes and half a minute which are actually 30 seconds. This is exactly what is returned by

>>> total_seconds % 60
30

Note also // is the floor division (returns the chopped of integer part of the standard division /).

Stefan
  • 1,697
  • 15
  • 31