[Python] 我需要将前 3 个变量(攻击、生命值、金钱)设置为全局变量,但我不知道怎么做,因为它们是随机的 (random.randint)。有人能告诉我代码应该是什么吗?谢谢!
编辑:我的错误类似于脚本后面的“赋值前引用的局部变量‘money’”。
这是完整脚本的链接:http://dl.dropbox.com/u/55052881/fightprogram.txt
抱歉,如果真的马虎,我一周前才开始学习 python。
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
最佳答案
我假设您发布的代码在一个函数内?如果是,您应该返回值而不是使用全局变量:return attack, hitpoints, money
返回包含这三个值的元组。
否则,您可以通过使用 global
语句在函数内部定义它来写入到全局范围内的变量:
global attack, hitpoints, money
顺便说一下,没有 global
也可以读取,修改可变对象也是如此。
关于Python - 你如何使这个 block 中的变量成为全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8675177/