[Tutor] print question

Ian Witham witham.ian at gmail.com
Tue Oct 9 04:45:26 CEST 2007


>
>
> Thanks!
>
> So now I have
>
> def secsToHMS(seconds):
>      """
>      Convert seconds to hours:minutes:seconds, with seconds rounded
> to hundredths of a second, and print
>      """
>      hours, minutes = 0, 0
>      if seconds >= 60 and seconds < 3600:
>          minutes, seconds = divmod(seconds, 60)
>      elif seconds >= 3600:
>          hours, seconds = divmod(seconds, 3600)
>          minutes, seconds = divmod(seconds, 60)
>      seconds = str(round(seconds,2)).split('.')
>      print seconds
>      print seconds[0]
>      hundredths = seconds[1]
>      print hundredths
>
>      print "%02d:%02d:%02d.%02d" % (int(hours), int(minutes),
> int(seconds[0]), int(seconds[1]))
>
> secsToHMS(4789.3459876)
>
> Which prints 01:19:49.35
>
> Any improvements in the function to suggest?


Don't need that conditional. Try this:

    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)

and you don't need the 'hundredths"...
hours and minutes are already integers (you don't need to convert them to
int in your string formatting) and seconds is a float. (if you supplied a
float to the function)

Try %f for formatting a float.

With these changes you could get your function down to 3 or 4 lines of code.

Also, it is generally better form to return a value than to have the
function do the printing, then you could print the result like this:

print secsToHMS(4789.3459876)

Ian
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071009/62855c51/attachment.htm 


More information about the Tutor mailing list