简体   繁体   中英

Generate new random numbers each time variable is used?

I just noticed, that when I run this code:


import random
import time

delay = random.randint(1,5)

for x in range(1, 101):

    print(x)
    time.sleep(delay)

The delay variable will be always the same since it is determined at the beginning. Is there any way to generate a new random number between 1 and 5 for delay variable in each loop? Now, obviously I could do something like this:


import random

import time

for x in range(1, 101):

    print(x)
    time.sleep(random.randint(1,5))

But I want to use variables since I have a huge code and do not want to go through all of it, if I change something. Many thanks in advance!

Your best bet is to define your own function to do the sleeping. That way you can change it whenever you like without having to the touch the rest of the code. For example:

def my_sleep():
    time.sleep(random.randint(1,5))

Then you can replace the calls to time.sleep(delay) with:

my_sleep()

You'd need to replace them all once, but after that you could change my_sleep without having to change them all again.

Use a mix of your approach and @TomKarzes :

small_delay = 5
big_delay = 10
huge_delay = 30

def my_sleep(delay):
    time.sleep(random.randint(1, delay))

When appropriate you can use

my_sleep(small_delay)    # 1-5 seconds

or

my_sleep(big_delay)      # 1-10 seconds

in your code. If you want to make changes to the overall delay-ranges you modify the variables on top.

Not sure what you try to achieve but the only thing you can do is make delay a function:

import random

def delay():
  return random.randint(1,5)

for x in range(1, 101):
    print(x)
    time.sleep(delay())

If this your current scenario with all referenced to the same delay :

...omitted...
delay = random.randint(1,5)

#first for loop
for x in range(1, 101):
    print(x)
    time.sleep(delay)

#another for loop
for x in range(1, 101):
    print(x)
    time.sleep(delay)

...so on...
for x in range(1, 101):
...omitted...

I'm afraid you cannot do it without requiring gargantuan of work.

This way the loop will be forced to use a new random seed each time the loop is iterated, which leads to a higher probability that the time of delay will be different at each iteration. Hope I understood your question.

import random
import time

for x in range(1, 101):
    random.seed(x)
    delay = random.randint(1,5)
    print(x)
    time.sleep(delay)
import random
import time

for x in range(1, 101):
    delay = random.randint(1,5)
    print(x)
    time.sleep(delay)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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