View Single Post
Old Sep 25th, 2005, 12:55 PM   #3
Cerulean
Professional Programmer
 
Cerulean's Avatar
 
Join Date: Apr 2005
Location: London, England
Posts: 459
Rep Power: 4 Cerulean is on a distinguished road
Quote:
they can't return a value for a global variable!
Sure they can, but you're not returning a value. You're trying to set the value of a global variable in your function. Python can also do this, but you need to use the global keyword in your function to tell Python that you're referring a global "answer" variable, not a local one that you just created, so your function would be:
def questions(q,ansone,anstwo,ansoneres,anstwores,ansunknown):
    global answer
    questionloop = 0
    while questionloop != 3:
        ans = raw_input(q)
        if ans == "inven":
            print inventory
        elif ans == ansone:
            print ansoneres
            questionloop = 3
            answer = 1
        elif ans == anstwo:
            print anstwores
            questionloop = 3
            answer = 2
        else:
            print ansunknown
With that said, you should be returning a value from the function, not setting a global variable and checking it from somewhere else - that will get very messy and very difficult to maintain. You want to be returning a value from the function:
inventory = [ "cat" , "gun" , "wallet" , "condom" ]

def questions(q, ansone, anstwo, ansoneres, anstwores, ansunknown):
    questionloop = 0
    while questionloop != 3:
        ans = raw_input(q)
        if ans == "inven":
            print inventory
        elif ans == ansone:
            print ansoneres
            questionloop = 3
            return 1
        elif ans == anstwo:
            print anstwores
            questionloop = 3
            return 2
        else:
            print ansunknown

answer = questions("Where is my cat?! :", "dead", "alive", "NOOOOOOOO!", "THANK GOD!", "WTF?!")
...
Cerulean is offline   Reply With Quote