Python Version of My Java Homework
Jan. 17th, 2009 05:25 pm![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
![[livejournal.com profile]](https://www.dreamwidth.org/img/external/lj-userinfo.gif)
However, she also has a copy of "Beginning Python From Novice To Professional" by Magnus Lie Hetland lying around. Since Python is the language I want to make actual real projects in, I was curious. So I decided to do my homework again, in Python. This time it was six lines long.
However, I decided to take it further. The new version properly uses singular and plural English. In other words, it will say "1 hour" instead of "1 hours."
totalSeconds = input("How many seconds?") hours = totalSeconds / 3600 remainingSeconds = totalSeconds % 3600 minutes = remainingSeconds / 60 seconds = remainingSeconds % 60 if hours == 1: pluralHour = "" else: pluralHour = "s" if minutes == 1: pluralMinute = "" else: pluralMinute = "s" if seconds == 1: pluralSecond = "" else: pluralSecond = "s" print str(hours) + " hour" + str(pluralHour) + ", " + str(minutes) + " minute" + str(pluralMinute) + ", and " + str(seconds) + " second" + str(pluralSecond) + "."
So while I was doing this, she also did the exercise in Python, except she didn't want to type the singlular/plural decision into her version three times like I did. She felt it was more elegant to make one set of pluralization instructions and have Python repeat it for hours, minutes, and seconds. She cursed at the computer for a half hour and came up with the version she will post in the comments.
I do not curse at the computer. I expect coding to be painful, and have been pleasantly surprised to be proven wrong.
pain = False
if not pain:
gain = False
no subject
Date: 2009-01-18 02:32 am (UTC)This:
Is the same as this:
I think the second actually shows a little more clearly what is being done, especially in cases like this where the if clause is short. (When the if clause is really long, it tends to make the lines get unreadably long when you do it this way)
In lojban terms, think of it as a sort of SE variety of conditianals -- the x2 gets rotated out to the front and then x1 and x3 follow. Or I also think of it as "inside out" notation, because the part that's normally in the middle comes first.
no subject
Date: 2009-01-18 02:53 am (UTC)no subject
Date: 2009-01-18 03:46 am (UTC)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: 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?
no subject
Date: 2009-01-18 08:31 am (UTC)no subject
Date: 2009-01-18 04:08 pm (UTC)no subject
Date: 2009-01-18 04:58 pm (UTC)What other programming languages have you used?
no subject
Date: 2009-01-18 06:36 pm (UTC)