简体   繁体   English

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

[英]How do I store a random integer in a local variable in Python?

I have some code here for a basic game I'm making in Python 3.x. 我在这里有一些代码用于我在Python 3.x中制作的基本游戏。 As you can see, the local variable 'code1' creates a random two digit number between my values, for the first part of my vault's unlock code (later in game). 正如您所看到的,局部变量'code1'在我的值之间创建了一个随机的两位数字,用于我的保险库解锁代码的第一部分(后来在游戏中)。 What I want to do is store the random integer somehow so if the specific room is re-visited it will display the first outputted random number from this function and not keep changing as this would defeat the object of clue collecting. 我想要做的是以某种方式存储随机整数,所以如果重新访问特定房间,它将显示该函数的第一个输出随机数,而不是保持变化,因为这将打败线索收集的对象。

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

Cheers guys. 干杯伙计们。

I suggest you add an attribute to the corridorOptions function that is only initialised once when it is created on the first call of the function 我建议你添加到属性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()

output 产量

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM