1
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()

我在 Python 中乱搞,我希望我的程序生成随机数。如您所见,我已经完成了这项工作。我想做的下一件事是让它生成多个随机数,这取决于“用户”想要生成多少个数字。我该怎么做呢?我假设需要一个循环。

4

5 回答 5

7

这将产生范围内的随机整数number1列表number2

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

有关更多信息,请查看列表理解。

于 2013-11-05T00:22:31.150 回答
1

使用生成器和迭代器:

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)
于 2013-11-05T02:34:27.323 回答
1

使用“for”循环。例如:

for i in xrange(times):
    # generate random number and print it
于 2013-11-05T00:17:38.593 回答
1

我建议使用一个简单地添加到现有字符串的循环:

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
于 2017-10-26T04:28:59.950 回答
-2

此代码选择一个随机数:

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

重复代码 6 次以选择 6 个随机数。

于 2017-06-12T09:10:25.577 回答