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

时间:2014-09-23 21:49:36

标签: 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) + "'")

干杯。

1 个答案:

答案 0 :(得分:3)

我建议您在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'