As requested, here is my code. Let me just say that at least half of the cursing was from Matt's request *after* I had coded it the first time, to display my loop in the same format as his did, with the same spacing, punctuation, and pluralization. ;P
The print function -- which I had used originally -- has extra spaces by default that make the same formatting in a loop impossible to implement. Here's what I came up with:seconds = input('Enter the number of seconds: ')
time = [("hour",seconds/3600), ("minute",(seconds%3600)/60), ("second",(seconds%3600)%60)]
result = '' for index,item in enumerate(time): name,value = item if value != 1: name = name + "s" if index == len(time)-1: result += "and " result += `value` + " " + name if index != len(time)-1: result += ", "
print "\t", result I've read that using index to refer to loops is not very Pythonic (damn you, Java, for corrupting me!). Is there another way that I could run the loop without making explicit [numerical] reference to the last item of the list?
The print function -- which I had used originally -- has extra spaces by default that make the same formatting in a loop impossible to implement. Here's what I came up with:seconds = input('Enter the number of seconds: ')
time = [("hour",seconds/3600), ("minute",(seconds%3600)/60), ("second",(seconds%3600)%60)]
result = ''
for index,item in enumerate(time):
name,value = item
if value != 1:
name = name + "s"
if index == len(time)-1:
result += "and "
result += `value` + " " + name
if index != len(time)-1:
result += ", "
print "\t", result
I've read that using index to refer to loops is not very Pythonic (damn you, Java, for corrupting me!). Is there another way that I could run the loop without making explicit [numerical] reference to the last item of the list?
Reply
Leave a comment