2013-11-05 280 views
-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中搞亂了,我想讓我的程序生成隨機數。正如你所看到的,我已經完成了這一點。接下來我想要做的是讓它生成多個隨機數,這取決於「用戶」想要生成多少個數字。我會如何去做這件事?我假設需要一個循環。Python多次的隨機數

+3

所以[閱讀環路(http://docs.python.org/2/tutorial/controlflow.html)寫一個循環,然後回報! – user2864740

+0

如果number1> number2,你將得到'ValueError' –

回答

1

使用「for」循環。例如:

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

這將產生一系列number1隨機整數的列表number2

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

欲瞭解更多信息,看看List Comprehension.

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) 
-2

此代碼選擇一個rando m號碼:

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

重複該代碼6次以選擇6個隨機數。

0

我會建議使用一個循環,只會增加現有的字符串:

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