2012-03-15 179 views
1

你好,我剛剛開始用Python編程,我只是想做一個RNG,但有一些我不明白的錯誤。Python隨機數生成器錯誤

下面的代碼

import random 
import time 

numbersGenerated = 0 

print('Hello! How many numbers do you want?') 
numbersNeeded = input() 
print('What would you like the minimum for the numbers be?') 
Min = input() 
print('And the maximum?') 
Max = input() 

numbersNeeded = str(numbersNeeded) 
numbersGenerated = str(numbersGenerated) 

while numbersGenerated < numbersNeeded: 
    number = random.randint(Min, Max) 
    number = int(number) 

    numbersGenerated = numbersGenerated + 1 

    print(number) 
    print() 
    time.sleep(2) 

print('All done. Hope to see you again!') 

回溯錯誤說

File "C:/Python32/Number_Generator.py", line 20, in <module> 
number = random.randint(Min, Max)  
File "C:\Python32\lib\random.py", line 215, in randint 
return self.randrange(a, b+1) 
TypeError: Can't convert 'int' object to str implicitly 

我已經改變了線十三先令也爲int但這並沒有改變結果。

回答

1

在Python 3,你應該輸入從input顯式轉換:

Min = int(input()) 

Max = int(input()) 
4
  1. 你正在做while numbersGenerated < numbersNeedednumbersGeneratednumbersNeeded是字符串,這可能不是你想要什麼。

  2. 您在致電random.randint(Min, Max),而MinMax是字符串,它們應該是整數。

  3. 不需要number = int(number),它已經是一個整數。

  4. numbersGenerated = numbersGenerated + 1再次,該變量是一個字符串