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中乱搞,我希望我的程序生成随机数。如你所见,我已经完成了这个。接下来我要做的是让它生成多个随机数,具体取决于“用户”想要生成的数量。我该怎么做呢?我假设需要一个循环。
答案 0 :(得分:1)
使用“for”循环。例如:
for i in xrange(times):
# generate random number and print it
答案 1 :(得分:1)
这将生成范围number1
到number2
rnumber = [random.randint(number1, number2) for x in range(times)]
有关详细信息,请查看List Comprehension.
答案 2 :(得分: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)
答案 3 :(得分: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
答案 4 :(得分:-2)
此代码选择一个随机数:
import random
x = (random.randint(1, 50))
print ("The number is ", x)
重复代码6次,选择6个随机数。