我猜测了Python 3.6中的数字程序,这是我的代码。
import random
guesses = 0
print('Hello! What is your name?')
name = input()
num = random.randint(1,10)
print('well',name,'I am thinking of a number between 1 and 20.')
while guesses < 4:
print('Take a guess.')
guess = input()
guess = int(guess)
guesses = guesses + 1
if guess < num:
print('Your guess is too low.')
if guess > num:
print('Your guess is too high.')
if guess == num:
guesses = str(guessesTaken)
print('Good job, ',name,'! You guessed my number in ',guesses,' guesses!')
if guess != num:
num = str(num)
print('Nope. The number I was thinking of was ',num)
当我运行我的代码时,它会显示此错误消息
Hello! What is your name?
h
well h I am thinking of a number between 1 and 20.
Take a guess.
7
Your guess is too low.
Nope. The number I was thinking of was 10
Take a guess.
5
Traceback (most recent call last):
File "C:\Users\user\Desktop\Number game.py", line 13, in <module>
if guess < num:
TypeError: '<' not supported between instances of 'int' and 'str'
为什么它支持&gt;但不是&lt; ? 感谢所有帮助。
答案 0 :(得分:0)
在Python中,print
函数很乐意将对象转换为字符串,您不需要这样做。在此代码的情况下,您尝试在打印之前将对象转换为字符串,破坏了变量供以后使用。所以,只需删除这两行,您的代码似乎工作正常:
guesses = str(guessesTaken)
num = str(num)