Wednesday, March 6, 2013

Assignment - Python

So, one of my java classes had this assignment a while back to write a command-line application to store user input to a text file. Easy, right? Just loop over the 3 questions and save the user responses on a line in a text file.

Having never worked with Java before, I was surprised at the amount of code necessary to do this. Even without validating user input, the code ended up being around 40 lines.

It got me thinking about how I would do the same thing in python. And I was curious to see how few lines it would take to get the exact same functionality. Here's what I came up with:

file = open("output.txt", 'w')
listOfStuff = []
while True:
    productID = raw_input("enter productID: ")
    product = raw_input("enter product: ")
    price = raw_input("enter price: ")
    listOfStuff.append(productID+" "+product+" "+price+ "\n")
    blah = raw_input("Coninue? yes or no: ")
    if blah in ("no", "nope", "negative"):
        break
for i in listOfStuff:
    file.write(i)
file.close()

13 lines does it. Sure I should do some input validation and all that best-practice jazz, but I didn't have to implement any of that for the java project either, and I was just trying to get the same output and functionality.

If anyone wants to see the crappy java version of this that I did, I guess I could post that too, just leave a comment, or shoot me a message. I only leave it out because 1) I'm lazy, and 2) I have my doubts about anyone actually reading this blog.

-newt

No comments:

Post a Comment