-1

This question is mostly becase I cannot find any good Python examples on how just to keep a main instance etc, and I am trying not to grow into any bad habits, like I did when I started PHP. I started Python about 3 hours ago, have been going at it, mostly console, then I decided to try the lists when I was watching https://www.youtube.com/watch?v=2IEePwMAb5Y&list=PL0A9588F9B2C45B3A . It mostly kills that the code looks horrendously awful and presumably incorrect. Is there any places I can find some simple applications written as Python was intended to look and run?

Background: I wanted to think of a small little application that would just let me see if I could cycle and play with the arrays. So I made a grocery list organizer.

i = 0
v = []
vara = None
def view():
    indx = 1
    for i in v:
        print "Grocery #" + str(indx) + ": " + str(i)
        indx += 1
while vara != "end" and vara != "exit":
    vara = raw_input("Please enter a grocery: ")
    vara = str(vara)
    if vara == "view":
        view()
    elif vara[len(vara)-4: len(vara)] == " del":
        key = vara[0:len(vara) - 4]
        if key in v:
            v.remove(key)
            print "Deleted: " + key
        else:
            print "Error, " + key + " was not found in your list"
    elif (vara != "end" and vara != "exit") and len(vara) > 0:
        v.append(vara)
view()

It is more important for me to have the places to find some good examples, that is the most important. Also how would I create the instance to start and end if you could. Thank you very much if you can.

Justin
  • 43
  • 8
  • It's not very clear about what you're asking. From what I gather, it sounds like you're looking for a resource to start learning some Python syntax, and perhaps some more ideas from it. Usually people have a question specifically about the code they post and things that are wrong with it. You may wish to come up with a question you don't understand from the code sample above to make your question more concrete. One resource that looks promising: http://learnpythonthehardway.org/book/. – pseudoramble May 01 '13 at 00:55
  • http://www.d.umn.edu/~gshute/softeng/principles.html, http://en.wikipedia.org/wiki/Software_design, i think the theory of design is most important than the language, you can read some theory and practice in Python that concepts, also you can read the book Information Systems Architecture by Martin Fowler, i nice book, i'm reading it again ... – DGomez May 01 '13 at 00:57
  • You might also enjoy http://codereview.stackexchange.com – kojiro May 01 '13 at 01:11
  • Looking at random YouTube videos is generally not going to be the best way to learn Python, especially if you want (as you say) to avoid picking up bad habits and learn the way it was intended to look. I strongly, strongly recommend that if you haven't done so already, go through the [official tutorial](http://docs.python.org/2/tutorial/). – John Y May 01 '13 at 02:36
  • This is perfect, thank you very much @John Y. Thank you very much. – Justin May 01 '13 at 21:14

1 Answers1

3

To write better python code, the best way is to 1) write lots of python code 2) critique your own python code by asking 'how could this be written in a more pythonic way?' (To understand pythonic, read http://blog.startifact.com/posts/older/what-is-pythonic.html and http://www.python.org/dev/peps/pep-0020/ ) 3) Read the standard libraries, about list comprehensions and itertools and neat tricks, so you keep them in the back of your head. Python is a lot about making all common operations a one liner/single function.

Here are my thoughts on your code:

i = 0

Global variable initialization with a bad name. Variables should either have a descriptive name or be a temporary iteration variable (in which case i, j, k, etc are all ok)

v = []

Global variable initialization with a bad name. What is 'v'? If you read your code 3 months from now, you would have no idea what this is for yet. Also, variables should be initialized inside of a class or function whenever possible (for OOP encapsulation).

vara = None

Global variable initialization with a bad name. What is 'vara'? If it is not needed to have global state, you should not define it on a global level. You should define variables where and when they are to be used, with fitting names.

def view():
    indx = 1
    for i in v:
        print "Grocery #" + str(indx) + ": " + str(i)
        indx += 1

Instead of having two separate iteration variables, use enumerate() to return tuples of index and item. http://docs.python.org/2/library/functions.html#enumerate

As in

def view():
    for i, item in v.iteritems():
        print "Grocery #" + str(i) + ": " + str(item)

Much nicer! It (optionally) doesn't even need its own method at this point, since it's a two liner.

while vara != "end" and vara != "exit":

Should be wrapped in a function and called if name == "main". As in What does if __name__ == "__main__": do?

Ah, that is what vara is for. You should call it something more descriptive - command, action, usercommand, whatever. vara is meaningless to me.

    vara = raw_input("Please enter a grocery: ")
    vara = str(vara)

I am pretty sure this line is unnecessary - won't raw_input only be able to return a string, anyway?

    if vara == "view":
        view()
    elif vara[len(vara)-4: len(vara)] == " del":
        key = vara[0:len(vara) - 4]

I can't think of a specific way to rewrite this, but it 'smells' hacky. (Maybe it's the fact that you're doing all your command parsing by doing substrings and indexofs and stuff, rather than using a proper structured way. But, everyone starts out like this :) )

        if key in v:
            v.remove(key)
            print "Deleted: " + key
        else:
            print "Error, " + key + " was not found in your list"
    elif (vara != "end" and vara != "exit") and len(vara) > 0:
        v.append(vara)
view()
Community
  • 1
  • 1
Patashu
  • 21,443
  • 3
  • 45
  • 53
  • Thank you very much. Very much I will see what happens once I finish the other read, and format my code. Thank you for taking your time to explain this to me. Thank you very much. – Justin May 01 '13 at 01:12
  • @Justin I think I am done editing the post now. Good luck and have fun :) – Patashu May 01 '13 at 01:13
  • Thank you, do you have any places for examples on stuff? Especially the part on the hacky part, is there a place I can find some examples on structuring that part? – Justin May 01 '13 at 01:26
  • @Justin Well, you can define a formal grammar in Python by using a lexer/parser such as PLY. That might be overkill for small applications though. For something simple but clear, you'd want to have each command run the same way - a one word command (possibly indicated by some special character before or after it), and the rest of it treated as input to that command. You'd switch on command and call a method for that command (e.g. using a dictionary of command names to their functions) passing the input. Something like that. – Patashu May 01 '13 at 01:31
  • Thank you very much. I hope Python comes as easy as its mystical myths are :D. – Justin May 01 '13 at 01:36