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

2024-09-28 12:12:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我这里有一些我用python3.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) + "'")

干杯伙计们。在


Tags: 函数代码游戏方式it整数python3房间
1条回答
网友
1楼 · 发布于 2024-09-28 12:12:54

我建议您向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()

输出

^{pr2}$

相关问题 更多 >

    热门问题