So I'm making a small text-game and one of the things I want to do is to get a random number from a range of variables.
For testing purposes I've written a code looks something like this:
slow_speed = random.randrange(10,25)
medium_speed = random.randrange(26, 50)
fast_speed = random.randrange(51, 75)
penalty_list = [slow_speed, medium_speed, fast_speed]
for i in range(3):
for penalty in penalty_list:
print(penalty)
The idea is that it would loop over the list 3 times and each time give a different random number for each range.
However, what happens is that I get the same 3 numbers looped 3 times. I figured it was because the seed(time on my computer) is the same when I invoke the function, so I've tried to add a time.sleep() and a random.seed() but that didn't help.
So how can I fix this? Thanks!
You need to put the variable declarations inside the for
loop. This way, random numbers are generated during each iteration. The following is probably what you are looking for:
import random
for i in range(3):
slow_speed = random.randrange(10,25)
medium_speed = random.randrange(26, 50)
fast_speed = random.randrange(51, 75)
penalty_list = [slow_speed, medium_speed, fast_speed]
for penalty in penalty_list:
print(penalty)
Sample Output
13
31
63
17
26
61
16
46
67
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With