注册 登录
编程论坛 Python论坛

请教:Python入门-Number Guessing Game 错误

dan2019 发布于 2019-11-20 10:00, 1743 次点击
刚刚开始入门Python,照着书录入,是一个Number Guessing Game,但还是遇到了错误。书里的程序是Python2.7.3下运行的,我是在Python3.7.3运行的,不知道有没有关系。以下是我按照书本录入的code:
import random
secret = random.randint(1,99)
guess = 0
tries = 0
print ("AHOY! I'm the Dread Pirate Roberts, and I have a secret!")
print ("It is a number from 1 to 99. I'll give you 6 tries.")
while guess != secret and tries < 6:
    guess = input ("what's your guess?")
    if guess < secret:
        print ("Too low, ye scurvy dog!")
    elif guess > secret:
        print ("Too high, landlubber!")

    tries = tries + 1

if guess == secret:
    print ("Avast! Ye got it! Found my secret, ye did!")
else:
    print ("No more questions! Better luck next time, matey!")
    print ("The secret number was, secret")

运行之后,有一个错误提示:
Traceback (most recent call last):
  File "D:/Python/Python Practice/Number-guessing Game.py", line 9, in <module>
    if guess < secret:
TypeError: '<' not supported between instances of 'str' and 'int'


请教各位:该怎样修改code?非常感谢!
4 回复
#2
fall_bernana2019-11-20 11:59
以下是引用dan2019在2019-11-20 10:00:04的发言:

刚刚开始入门Python,照着书录入,是一个Number Guessing Game,但还是遇到了错误。书里的程序是Python2.7.3下运行的,我是在Python3.7.3运行的,不知道有没有关系。以下是我按照书本录入的code:
import random
secret = random.randint(1,99)
guess = 0
tries = 0
print ("AHOY! I'm the Dread Pirate Roberts, and I have a secret!")
print ("It is a number from 1 to 99. I'll give you 6 tries.")
while guess != secret and tries < 6:
    guess = input ("what's your guess?")
    if guess < secret:
        print ("Too low, ye scurvy dog!")
    elif guess > secret:
        print ("Too high, landlubber!")

    tries = tries + 1

if guess == secret:
    print ("Avast! Ye got it! Found my secret, ye did!")
else:
    print ("No more questions! Better luck next time, matey!")
    print ("The secret number was, secret")

运行之后,有一个错误提示:
Traceback (most recent call last):
  File "D:/Python/Python Practice/Number-guessing Game.py", line 9, in <module>
    if guess < secret:
TypeError: '<' not supported between instances of 'str' and 'int'

请教各位:该怎样修改code?非常感谢!

返回的错误表示在第9行 不能在字符串和整数之间做<操作. 你需要int(str)后再做< 比较操作
#3
dan20192019-11-20 13:27
回复 2楼 fall_bernana
您能再具体一些吗?我是指,具体怎样修改第9行呢?谢谢!
#4
fall_bernana2019-11-20 14:06
回复 3楼 dan2019
guess = int(input ("what's your guess?"))
#5
dan20192019-11-21 11:07
回复 4楼 fall_bernana
太感谢了!!!
1