Python-Error:"int"或"str"不支持">"和"<"



我的代码中遇到错误,我无法在输入机制中使用<或>。我的目标是用 5 次尝试猜测数字来猜测数字游戏,但这个错误不允许我实现提示玩家猜测更高或更低的机制!任何帮助请求!

我的代码:

n = 1
rolltime = 0
import random
def rolldice(n):
dice = []
for i in range(n):
dice.append(random.randint(1,50))
return dice
roll = rolldice(n)
print("Try to guess my number! You have 5 tries! It is between 1 and 50.")
rolldice(n)
while rolltime < 6:
rollguess = int(input("What do you think it is? "))
if rollguess == roll:
print("You guessed it! Good job!")
rolltime = rolltime + 6
else:
if rollguess < roll:
print("Your guess was too low! Try again. ")
elif rollguess > roll:
print("Your guess was too high! Try again.")
rolltime = rolltime + 1

我收到的错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-12-78e886a91aa0> in <module>
16         rolltime = rolltime + 6
17     else:
---> 18         if rollguess < roll:
19             print("Your guess was too low! Try again. ")
20         elif rollguess > roll:
TypeError: '<' not supported between instances of 'int' and 'list'

正如 Ian 评论的那样,您正在尝试将数字与数字列表进行比较。如果你想将他们猜到的数字与列表中的第一个数字进行比较,你可以尝试类似dice[0]来获取列表中的第 0 个(第一个(元素:

n = 1
rolltime = 0
import random
def rolldice(n):
dice = []
for i in range(n):
dice.append(random.randint(1,50))
return dice
roll = rolldice(n)
print("Try to guess my number! You have 5 tries! It is between 1 and 50.")
rolldice(n)
while rolltime < 6:
rollguess = int(input("What do you think it is? "))
if rollguess == roll[0]:
print("You guessed it! Good job!")
rolltime = rolltime + 6
else:
if rollguess < roll[0]:
print("Your guess was too low! Try again. ")
elif rollguess > roll[0]:
print("Your guess was too high! Try again.")
rolltime = rolltime + 1

但是,如果旨在使变量dice包含游戏的可能答案,则必须将答案存储在单独的变量中,如下所示:

# ...
n = 1
dice = rolldice(n)
answer = random.choice(dice) # Obviously, this is the same as accessing dice[0] for  n=1
# ...
if (rollguess == answer):
# ... etc

您无法比较列表和数字。

rolltime = 0
import random
def rolldice():
return random.randint(1,50)
roll = rolldice()
print("Try to guess my number! You have 5 tries! It is between 1 and 50.")
while rolltime < 6:
rollguess = int(input("What do you think it is? "))
if rollguess == roll:
print("You guessed it! Good job!")
rolltime = rolltime + 6
else:
if rollguess < roll:
print("Your guess was too low! Try again. ")
elif rollguess > roll:
print("Your guess was too high! Try again.")
rolltime = rolltime + 1

我尝试简化函数以避免您的列表问题。还添加了参数以提高灵活性。

import random
def roll_dice(min_num=1, max_num=50, max_guess=6):
roll = random.randint(min_num,max_num)
#print(roll)  for testing purposes only
print(f'Try to guess the number! You have {max_guess} tries!
It is between {min_num} to {max_num}.')
while max_guess != 0:
rollguess = int(input('What do you think it is? '))
if rollguess == roll:
print("You guess it right! Good job!")
break
elif rollguess < roll:
print("You're guess is too low! Try again. ")
max_guess -= 1
else:
print("You're guess is too high! Try again. ")
max_guess -= 1
roll_dice()

最新更新