[Python] I need to make the first 3 variables (attack, hitpoints, money) global but i dont know how because they are random (random.randint). Could someone tell me what the code should be? Thanks!
Edit: My error is something like “local variable ‘money’ referenced before assignment” later in the script.
Heres a link to the full script: http://dl.dropbox.com/u/55052881/fightprogram.txt
Sorry if it’s really sloppy, i just started learning python a week ago.
while roll == 1:
attack = random.randint(1, 100)
hitpoints = random.randint(1, 500)
money = random.randint(1, 1000)
attackstr = str(attack)
hitpointsstr = str(hitpoints)
moneystr = str(money)
print()
print('Your attack level is ' + attackstr + '.')
print('You have ' + hitpointsstr + ' hitpoints.')
print('Your have ' + moneystr + ' coins.')
print()
print('Type 1 to reroll.')
print('Type 2 to proceed.')
reroll = input()
reroll = int(reroll)
if reroll == 2:
break
I think you misunderstand what it means for a variable to be global. I strongly suggest reading through Python’s documentation on scopes and namespaces, but I will do my best to summarize in a way that is relevant to your problem.
A “global variable” is a variable that is in the global namespace. There is a separate global namespace for each module. Besides modules, classes and functions are the only things that will create new scopes. Any new variables you create will be placed in the innermost scope.
There is a global keyword, which can be used to reference global variables, but this is only necessary when you are assigning to a global variable, for example:
In your isolated code example,
attack,hitpoints, andmoneyare already global variables because they are not in any other scope, and they will be modified in each run of the loop. If your code is actually in a class or a function, then adding the lineglobal attack, hitpoints, moneyto the top of that scope will result in these variables being set in the global namespace for your module.