Python random numbers multiple times

不羁岁月 提交于 2021-02-08 06:45:32

问题


import random

def main():
    uinput()

def uinput():
    times = int(input('How many numbers do you want generated?'))
    number1 = int(input('Put in the first number:' ))
    number2 = int(input('Put in the second number:'))
    rnumber = random.randint(number1, number2)
    print (rnumber)



main()

I am messing around in Python, and I want my program to generate random numbers. As you can see I have already accomplished this. The next thing I want to do is have it generate multiple random numbers, depending on how many numbers the "user" wants generated. How would I go about doing this? I am assuming a loop would be required.


回答1:


This will produce a list of random integers in range number1 to number2

rnumber = [random.randint(number1, number2) for x in range(times)]

For more information, look at List Comprehension.




回答2:


Use a "for" loop. For example:

for i in xrange(times):
    # generate random number and print it



回答3:


Use generators and iterators:

import random
from itertools import islice

def genRandom(a, b): 
    while True:
        yield random.randint(a, b)


number1 = int(input('Put in the first number:' ))
number2 = int(input('Put in the second number:'))
total = int(input('Put in how many numbers generated:'))

rnumberIterator = islice(genRandom(number1, number2), total)



回答4:


I would recommend using a loop that simply adds to an existing string:

import random
from random import randint
list=""
number1=input("Put in the first number: ")
number2=input("Put in the second number: ")
total=input("Put in how many numbers generated: ")
times_run=0
while times_run<=total:
    gen1=random.randint(number1, number2)
    list=str(list)+str(gen1)+" "
    times_run+=1
print list



回答5:


This code chooses a random number:

import random
x = (random.randint(1, 50))
print ("The number is ", x)

Repeat the code 6 times to choose 6 random numbers.



来源:https://stackoverflow.com/questions/19779737/python-random-numbers-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!