Python - 你如何使这个 block 中的变量成为全局变量?

标签 python random global-variables global

[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/

相关文章:

python - SWIG 中的垃圾收集和自定义 getter

swift - arc4random Swift 3 语法

c++ - 我的柏林噪音看起来不对,几乎就像灰色 T 恤 Material (石南花)。为什么?

python - 类变量在python中的所有实例之间共享?

css - Angular 组件的全局 scss 变量,无需每次都导入它们

python - 从 Pandas GroupBy 函数(和/或建议的其他方法)为 SVM 创建特征(行)向量

python : an integer is required (got type str)

java - 具有跨不同 Java 版本的恒定种子的 Random 的可靠性

python - 如何在Django View 中存储全局变量

python - python lxml 模块在内部使用哪种编码?