我猜了一下Python3.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'
为什么它支持但不支持? 感谢大家的帮助。
在Python中,
print
函数很乐意将对象转换为字符串,您不需要这样做。在这段代码中,您在打印之前试图将对象转换为字符串,破坏了变量以备以后使用。所以,只要删除这两行代码,代码就可以正常工作了:相关问题 更多 >
编程相关推荐