我正在尝试创建一个数字猜谜游戏,但我得到了“guessestaken”的错误我从http://inventwithpython.com/IYOCGwP_book1.pdf第57页复制了代码。我对python有点新鲜。
import random
guessestaken=0
print ("hello what ur name?")
myname=input()
number=random.randint(1,20)
print ("well " + myname + " i am thinking of a number guess it")
while guessestaken < 6 :
guessestaken=guessestaken+1
guess =input('take a guess')
guess = int(guess)
if guess <number:
print('too low')
if guess >number:
print ('too high')
if guess ==number:
break
if guess ==number:
guessestaken=str(guessestaken)
print ('good job ' + myname + ' you are right!')
print ('you guessed it in ' + guessestaken + ' guesses')
if guess !=number:
guessestaken = str(guessestaken)
print ("I am sorry but you couldn't get it right")
print ("you couldn't guess it in " + guessestaken + " guesses")
答案 0 :(得分:4)
错误消息是(试图)通知您,您正试图将str
与int
进行比较。特别是,应该有一个回溯通知您错误发生的位置:
Traceback (most recent call last):
File "./tmp.py", line 8, in <module>
while guessestaken < 6 :
您可以看到您明确地将guessestaken
转换为字符串:
guessestaken = str(guessestaken)
显然没有必要。如果要打印所采用的猜测数量,可以使用+
(不推荐使用或#34; pythonic&#34;)进行内联,也可以使用format
:
print('you guessed it in ' + str(guessestaken) + ' guesses')
print('You guessed it in {} guesses'.format(guessestaken))
答案 1 :(得分:3)
您正在将guesstaken
转换为字符串以显示它
guessestaken=str(guessestaken)
然后while
循环检查是否
while guessestaken < 6 :
导致类型错误(python无法比较字符串和 int )。 您应该只使用字符串的其他名称或使用python结构(如
)内联print('You guessed it in {} guesses'.format(guessestaken))