Home > front end >  Hello, I am having a problem with the "Random" library in python
Hello, I am having a problem with the "Random" library in python

Time:04-24

Hello I am having a problem with the "random" library in python. So basically I want it to return a value between (1, 99) so that part works but I want it to return multiple random values by only running the code once. It only gives me 1 random value for each run. Here is the code:

import random
import time
 
Random = random.randint(1, 99)
while True:
    time.sleep(0.7)
    print(Random)
    

And I also wanted to ask that how to time a function in python. If I only want it to run for a specific amount of time, how do I do that?

Thanks.

CodePudding user response:

import random
import time

while True:
    Random = random.randint(1, 99)
    print(Random)
    time.sleep(0.7)

If you want it to run as fast as possible for 0.7 seconds:

import random
import time

alarm = time.time()   0.7
while time.time() < alarm:
    Random = random.randint(1, 99)
    print(Random)

Note that this is a tight CPU loop, and thus is not a good idea, but it shows you the concept.

CodePudding user response:

If you want a list of random integers in a single call you can use choices or sample from the random standard library along with range to get what you want:

import random

# 10 random integers between 1-99 with replacement
print(random.choices(range(1, 100), k=10))

# 10 random integers between 1-99 without replacement
print(random.sample(range(1, 100), k=10))
[45, 52, 36, 43, 46, 28, 43, 37, 37, 17]
[63, 10, 40, 38, 86, 87, 65, 37, 15, 49]

CodePudding user response:

You can try this:

import random 
n = 20 
random_num_list = random.sample(list(range(1,99)), n) 

CodePudding user response:

This is because the random number using the random library was declared only once outside the while.

As you answer above, you can put random number generation into the while loop.

You can also check it using a for-loop.

from random import randint

for _ in range(10):
    random_num= randint(0, 10)
    print(random_num)

output

1
3
4
9
4
2
7
5
1
6

CodePudding user response:

Try this:

import random
for i in range(3):
    print(random.randint(1,99)

CodePudding user response:

    # Imports
    import random
    import time

    # Working
    while True:
        time.sleep(0.7)
        Random = random.randint(1, 99)
        print(Random)
  • Related