Home > Back-end >  Python random number loop with different outcomes each time
Python random number loop with different outcomes each time

Time:05-20

I’ve been working on a school project and need to do a loop consisting of a couple random numbers but I need them to output a different number each time. The code I’ve been using for the random numbers is this.

import random

a=random.randint(1,9)

I’m new to coding and just starting getting into python for fun and have looked everywhere for how to complete this loop but I can’t find anything that works.I know this code does not include a loop and the loop I was using before was “while True” and “for i in range” Thanks

CodePudding user response:

You have not created any loop yet. You're generating random integer only once. In order to generate more of them you have to use something like a for loop.

If you're familiar with the concept of range then this is a simple example of generating x-number of random integers.

import random

x = 10
for i in range(0, x):
    a = random.randint(1, 9)
    print(a)

CodePudding user response:

I am assuming you are doing something like this. Your loop needs to call the random.randint function on each iteration of the loop.

a = random.randint(1,9)

for i in range(5):
    print(a)

What you should be doing is this

for i in range(5):
    print(random.randint(1,9))

CodePudding user response:

If you want to have 5 values between 1 - 9 without repetition you can use the sample function of the random module. This will select n values from a list and store them in a new list.

array = random.sample(range(1, 9), 5)
for elem in array: 
    print(elem)

But if you want to have a new random value between 1 and 9 every iteration and you dont care if a number is repeated I would go with the answers the others already gave you.

CodePudding user response:

Random works with a seed, with the same seed the same output

Easiest way to achieve that you want, you will have a different seed each time you run your program

import random
from datetime import datetime
random.seed(datetime.now())
for _ in range(10):
    a=random.randint(1,9)
  • Related