Noob Python coder, need help

Started by
2 comments, last by fabianhjr 13 years, 6 months ago
Hey everyone, I'm trying to make a program where you enter what all you need to get from the grocery store. It then put's those items into a list, sorts the list than prints the list. This is the code I have as of right now..





def menu():
print "Welcome"
print "What would you like to do?"
print " "
print "1) Create"
print "2) Quit"
return input("Choose an option: ")

list = []

def add(raw_input):
list.append( (raw_input) )


loop = 1
choice = 0

while loop == 1:
choice = menu()
if choice == 1:
add(raw_input("Enter an item: "))
q = raw_input("Would you like to add another item? y/n: ")
if q == y:
add(raw_input("Enter an item: "))
if q == n:
loop = 0
elif choice == 2:
loop = 0
print "end"




When I run it, it runs normally, It allows me to enter my first item, and it puts it into the list, it than ask, "would you like to add another item? y/n

and if i hit either y or n it gives me this error..

Traceback (most recent call last):
File "C:\Python24\test1", line 23, in -toplevel-
if q == y:
NameError: name 'y' is not defined

I thought since i was using q = raw_input I figured it would work, i'm not too sure whats wrong. Can anyone help?
Advertisement
the problem in that comparison is that python is looking for a variable named y. You should instead use character 'y'. So:

q == 'y'
q == 'n'
Hey, thanks that helped a lot! is there anyway I can just loop that general area? because if I choose 'y' it will ask for another item, than I type the item in then it loops the whole entire code :\
Hello orbikk, I took the liberty of cleaning up your code.
Changes and explanations:

  • Multiline strings. Look at the code.EDIT: ''' '''

  • Don't forget to use raw_input for input.

  • When you receive input(Trough raw_input) you get it as a string even if it is a number.

  • You can use while as a conditional + loop. I am sure you will like that trick.:D

  • The function add is only called once in your whole code. It is better to take it off.


def menu():    print '''WelcomeWhat would you like to do?    1) Create    2) Quit''' #Maybe you will like this for multiline strings.    return raw_input("Choose an option: ") # Don't we learn? Use raw_input.list = []while 1:    choice = menu()    while choice == '1': #Don't forget we are getting chars and not ints. You will also like this one as a conitional. :D        list.append(raw_input("Enter an item: ")) # It is better if you don't define it as a function since you only call it once.        if(raw_input("Would you like to add another item? y/n: ")).lower() == ' n':break    if choice == '2':break #Don't forget we are getting chars and not ints.print "end"


Hope it helps :D

This topic is closed to new replies.

Advertisement