python - 如何在 Python 中的局部变量中存储随机整数?

标签 python python-3.x

我这里有一些用 Python 3.x 制作的基本游戏的代码。正如您所看到的,局部变量“code1”在我的值之间创建一个随机的两位数,作为我的金库解锁代码的第一部分(稍后在游戏中)。我想要做的是以某种方式存储随机整数,这样如果重新访问特定房间,它将显示该函数第一个输出的随机数,并且不会继续更改,因为这会破坏线索收集的对象。

def corridorOptions():
    code1 = random.randint(30,60)
    corridorChoice = input('> ')
    if corridorChoice == "loose":
        delayedPrint("You lift the loose floorboard up out its place." + '\n')
        delayedPrint("It shifts with hardly any resistance." + '\n')
        delayedPrint("There is a number etched. It reads " + "'" + str(code1) + "'")

干杯,伙计们。

最佳答案

我建议您向 corridorOptions 函数添加一个属性,该属性仅在首次调用该函数时创建一次初始化

from random import randint

def corridorOptions():
    if not hasattr(corridorOptions, 'code'):
        corridorOptions.code = randint(30, 60)
    print("There is a number etched. It reads '{0:02d}'".format(corridorOptions.code))


corridorOptions()
corridorOptions()
corridorOptions()
corridorOptions()
corridorOptions()

输出

There is a number etched. It reads '58'
There is a number etched. It reads '58'
There is a number etched. It reads '58'
There is a number etched. It reads '58'
There is a number etched. It reads '58'

关于python - 如何在 Python 中的局部变量中存储随机整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26005274/

相关文章:

python-3.x - 如何在Python的scipy信号卷积中添加比率参数?

python - 如果我将脚本命名为 'string.py' 或 'math.py',“导入”操作的行为会有所不同。为什么会这样?

python - 默认为并选择 Tkinter 列表框中的第一项

python魔杖错误 "wand.resource.DestroyedResourceError: <wand.image.Image: (closed)> is destroyed already"

python - 在cygwin中安装obspy

python - Python 中神秘的重复数组

python - 随机组合两个二叉树

python - 字母数字字符串的正则表达式,下划线不应是第一个或最后一个字符

html - 使用 bs4 查找和删除 HTML5 data-* 属性

python - 我正在尝试为基于文本的应用程序创建 tkinter 输出窗口