在Python中,如何在局部变量中存储随机整数?
我这里有一些代码,用于我正在用Python3.x制作的一个基本游戏。如您所见,局部变量“code1”在我的值之间创建一个随机的两位数,作为我的保险库解锁代码的第一部分(稍后在游戏中)。我想做的是以某种方式存储随机整数,这样,如果重新访问特定的房间,它将显示此函数输出的第一个随机数,并且不会一直更改,因为这将破坏线索收集的对象在Python中,如何在局部变量中存储随机整数?,python,python-3.x,Python,Python 3.x,我这里有一些代码,用于我正在用Python3.x制作的一个基本游戏。如您所见,局部变量“code1”在我的值之间创建一个随机的两位数,作为我的保险库解锁代码的第一部分(稍后在游戏中)。我想做的是以某种方式存储随机整数,这样,如果重新访问特定的房间,它将显示此函数输出的第一个随机数,并且不会一直更改,因为这将破坏线索收集的对象 def corridorOptions(): code1 = random.randint(30,60) corridorChoice = input('&
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'