类型错误:“str”和“int”的实例之间不支持“<”

2024-05-22 03:17:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python3创建一个文本游戏。

我的代码:

import random
secret = random.randint(1,99)
guess = 0
tries = 0
print (" AHOY! I'm the Dead 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 yer 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 guesses! Better luck next time, matey!")
    print ("The secret number was "), secret

跑步后,我得到

TypeError: '<' not supported between instances of 'str' and 'int'

当我输入40

我不知道为什么会这样。


Tags: and代码文本import游戏numbersecretif
1条回答
网友
1楼 · 发布于 2024-05-22 03:17:11

Python 3.x'input()函数默认返回int。为了获得类型为int的对象,需要显式地对其进行类型转换:

guess = int(input ("What's yer guess?"))

当前guess是字符串变量,secret是int,因此不能将运算符'<;'与字符串和int一起使用

更新代码:

import random
secret = random.randint(1,99)
guess = 0
tries = 0
print (" AHOY! I'm the Dead 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 = int(input ("What's yer 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 guesses! Better luck next time, matey!")
    print ("The secret number was "), secret

相关问题 更多 >