[Tutor] Help

Alan Gauld alan.gauld at btinternet.com
Thu Sep 6 11:15:19 CEST 2012

On 06/09/12 09:35, Ray Jones wrote:

>>> #A Python text-RPG
>>> #A Jak Production
>>> #APOC
>>> global ammo

You use global inside a function not outside. All variables declared at 
the module level are global by definition.

>>> ammo=55

This sets the global ammo value

>>> def part1():
>>>     if answer == "SHOW" or answer == "Show" or answer == "show":
>>>         answer2 = raw_input("Type either Hand it over or flee")
>>>         if answer2 == "HAND IT OVER" or answer2 == "Hand it over" or answer2
>>> == "hand it over":
>>>             print "Bandit: Good Job.. Go on now"
>>>             ammo=ammo-15

Here you try to create a local variable in the function butuse that 
variable in its definition.

What you really wanted was to use the global ammo. To do that you need 
to tell the function that any reference to ammo will use the global 
value, like this

def part1():
    global ammo

at the top of the function.

Ray added:
> I'll take a stab at it. You are using attempting to modify a global
> variable within a procedure. Procedure variables are separate from
> global variables. Global variables must be passed into a procedure using
> something on the order of 'part1(ammo)', and then returned back from the
> procedure with a 'return <value>'

That's not strictly true, as explained above. However, it is generally 
considered good programming practice not to rely on globals but to pass 
values in as parameters as you do in your example here.

So good practice says part1() should be defined as:

def part1(theAmmo, theFood, theLives):
     # as is code...

Notice I changed the names to distinguish them from the global variables.
and you call it using the global variables as:


The other thing to note is that at one point you use

return part1

That returns the function itself which is almost certainly not what you 

You also return answer3 which doesn't seem to be defined anywhere.
Returning lots of different values from the same function will make it 
very hard to use. You should think about breaking this down into the 
code that gets the user responses and separate code that returns the 
required values, one value per function.

And finally at the end you call part() from within part(), that's a 
technique called recursion and can get you into all sorts of problems if 
you don't know what you are doing with it.

What you really want is a loop that repeats the input code until you get 
valid values. A while loop is probably best in this case.

Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list