Python随机数生成器错误

时间:2012-03-15 22:50:37

标签: python

您好我刚刚开始使用Python进行编程,我只是想制作一个RNG但是有一些我不理解的错误。

这是代码

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

我已经改变了十三行和整数,但这并没有改变结果。

2 个答案:

答案 0 :(得分:4)

  1. while numbersGenerated < numbersNeedednumbersGenerated是字符串时,您正在numbersNeeded,这可能不是您想要的。

  2. 您正在呼叫random.randint(Min, Max)MinMax是字符串,它们应该是整数。

  3. 不需要number = int(number),它已经是一个int。

  4. 再次
  5. numbersGenerated = numbersGenerated + 1,变量是一个字符串

答案 1 :(得分:1)

在Python 3中,您应该明确地转换input的输入:

Min = int(input())

Max = int(input())