Pregunta

My code is uploaded on githib here:

https://github.com/GameWylder/MonolithGame/blob/Alpha/QfS%200.1.2a.py

So, what I'm trying to do is use a Global variable to track "Morality".

Now, it's not true moral choices, but I want to use it to track a players choices.

I basically have this setup:

morality = 0

def pick():
    while True:
        choice = input("")
        if choice == "Hesitate":
            hesitate() #hesitate() is defined already, i just didn't include it to save space.
            morality = 1
            break
        elif choice == "Walk":
            walk() #again, walk() is previously defined.
            morality = 2
            break
        else:
            print("Invalid Input")
#+#+#+#+#+#+#+#+#+#+#+#+#+#
#Clean Up
#+#+#+#+#+#+#+#+#+#+#+#+#+#

pick()
print(morality) #This is to see if the morality worked.

Sadly, it doesn't work. How can I properly set this up?

(My set up is this; the first choice will set the first number, 1 or 2, then the second choice sets the first decimal to either #.1 or #.2, then the third will do #.#1 or #.#2 etc, etc.)

What I mean by "it doesn't work" is this

>>>What's your choice?
Walk
>>>
>>>You Walk
>>>0

when it should be like

>>>What's your choice?
walk
>>>
>>>You Walk
>>>2
¿Fue útil?

Solución

When you perform an assignment to a variable name within a function, it will create a local variable unless the global statement is used. Try adding the following line to the top of your pick function:

global morality

Or better yet, just have your pick function return the morality value and then when you make the call use morality = pick().

For a more thorough explanation of the global statement, see this blog post:
http://freepythontips.wordpress.com/2013/07/28/the-use-of-return-and-global-keywords/

Otros consejos

Just to simplify your problem, look at this code:

morality = 0
def foo():
    morality = 99
    print "in foo:", morality

print "morality before foo:", morality
foo()
print "morality after foo:", morality

Which produces the output:

morality before foo: 0
in foo: 99
morality after foo: 0

Now try it with this version of foo():

def foo():
    global morality
    morality = 99
    print "in foo:", morality

I think the same issue applies to your code.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top