gpt4 book ai didi

python - 类型错误 : '<' not supported between instances of 'int' and 'str'

转载 作者:行者123 更新时间:2023-12-02 10:00:50 25 4
gpt4 key购买 nike

我已经猜测了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'

为什么支持 > 但不支持 < ?感谢所有帮助。

最佳答案

在Python中,print函数很乐意将对象转换为字符串,你不需要这样做。在此代码的情况下,您尝试在打印之前将对象转换为字符串,从而破坏了稍后使用的变量。因此,只需删除这两行,您的代码似乎就可以正常工作:

guesses = str(guessesTaken)

num = str(num)

关于python - 类型错误 : '<' not supported between instances of 'int' and 'str' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43691694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com