Skip to content Skip to sidebar Skip to footer

In Python, Is There Anyway To Have A Variable Be A Different Random Number Everytime?

Basically I have this: import random variable1 = random.randint(13, 19) And basically what that does is assign variable1 a random number between 13 and 19. Great. But, what I want

Solution 1:

This is close to what you want

>>>import random>>>variable1 = lambda: random.randint(13, 19)>>>print(variable1())
18
>>>print(variable1())
15
>>>print(variable1())
17
>>>

Solution 2:

Perhaps a silly question, but why not just use a function instead of a variable?

Or perhaps more inline with your variable paradigm, why not use a method on an object. The object can then be passed as a variable, and the method returns the new random number.

Solution 3:

In that specific example, there's a rather asinine way of doing it. print implicitly converts its argument into a string. You can overload that functionality:

classrandomizer():
    def__str__(self):
        returnstr(random.randint(13, 19))

variable1 = randomizer()
print(variable1)
print(variable1)
print(variable1)

Solution 4:

You mention the word "called", and in that way I think you have answered your own question. This is exactly the job of a function or method.

A variable is just a reference to an object. You could store an object in your variable which overrides the to string method in order to generate a random number, but this is still a method.

Ultimately what your asking for would be obfuscating what is really going on under the hood, and as a result would create less maintainable code, imho.


When you do variable1 = random.randint(13, 19), variable1 contains the immutable object "the number 13" (or some other number). By definition it cannot change without becoming another object. Instead you could fill your variable with an aforementioned mutable object allowing it to modify its "random number". Or you could just directly call a function.

Its simply a question of simplicity.

Solution 5:

use:

alist = range(13,20)  
random.shuffle(alist)  

Now you can loop through this in random order

Post a Comment for "In Python, Is There Anyway To Have A Variable Be A Different Random Number Everytime?"