使用randint()时出错,'TypeError:必须是str not int'

时间:2017-02-21 23:35:13

标签: python python-3.x

这是我的代码,它执行一个简单的猜数游戏:

i = 1
lower = input('Enter the lower range: ')
upper = input('Enter the upper range: ')
from random import randint
answer = randint(lower, upper)
guess = input("What's the number? ")
while guess != answer:
    if ~(guess in range(lower, upper)):
        print('Your guess must be in the range', lower, 'to', upper)
        i = i - 1
    elif guess < answer:
        print('Too low!')
    elif guess > answer:
        print('Too  high!')
    guess = input("What's the number? ")
    i = i + 1
print('Congrats! You correctly guessed the number to be ', answer, '! It took you ', i, ' tries.', sep='')

当我尝试运行它时,命令提示符给出了以下错误:

File "C:\Users\username\AppData\Local\Programs\Python\Python36-32\lib\random.py", line 220, in randint
    return self.randrange(a, b+1)
TypeError: must be str, not int

编辑:感谢您的解决方案,将input(...)更改为int(input(...))修复了我的代码。我还要补充说,第8行也包含错误。它应该是:if not (guess in range(lower, upper + 1)):

2 个答案:

答案 0 :(得分:1)

您需要先将输入转换为整数:

lower = int(input('Enter the lower range: '))
upper = int(input('Enter the upper range: '))

解释错误:错误消息有点误导,因为它表示您需要str而不是int,而不是相反。但是,它来自这样一个事实:在执行内部randrange函数之前,b会递增,因此您有例如'10'+1并且会生成此错误。

答案 1 :(得分:0)

您正在使用&#34;数字&#34;来自input()函数。

input()以字符串形式出现。您需要在值int(lower)之前使用randint()将其转换为数字形式。

(错误源于b+1 - randint尝试添加,但添加到字符串定义为连接,这需要两个字符串。)