這裏是我的代碼,它執行一個簡單的數字猜謎遊戲:錯誤「類型錯誤:必須str的不是int」
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)):
。
提示:在Python 3(不像蟒2),輸入返回一個字符串...做randint('1','5')返回一個類似於你得到的錯誤(我沒有python3方便)...你想要做upper = int(input(「.. ..「)),同樣對於更低的 – Foon
這個'if〜(猜測在範圍內(低,高)):'是'〜'運算符的一個非常用的用法。如果猜測不在範圍內(較低,較高):'或者更簡單一些,如果較低<=猜測<較高:',則更好。 – Matthias