thenovicecoder
thenovicecoder

Reputation: 45

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. 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). 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.

Upvotes: 1

Views: 1642

Answers (1)

Borodin
Borodin

Reputation: 126772

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

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'

Upvotes: 3

Related Questions