鱼C论坛

 找回密码
 立即注册
查看: 3257|回复: 4

[已解决]不知道问题在哪里,麻烦帮忙看看

[复制链接]
发表于 2023-8-9 17:20:31 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
import random

answer = random.randint(1, 10)
opportunity=0
while opportunity < 3:
    temp = input("请用户输入一个1到10的数字:")
    num=int(temp)
    if temp == answer :
        print("恭喜你答对了")
        break
    else:
        if temp < answer:
            print("小了")
        else:
            print("大了")
        opportunity = opportunity + 1
print("游戏结束!!!")

这个运行之后结果是这样的
请用户输入一个1到10的数字:4
Traceback (most recent call last):
  File "C:/Users/万苏荣2/Desktop/python/数字游戏.py", line 12, in <module>
    if temp < answer:
TypeError: '<' not supported between instances of 'str' and 'int'



最佳答案
2023-8-9 17:20:49
问题出在比较语句temp < answer上,报错提示是TypeError: '<' not supported between instances of 'str' and 'int',说明字符串和整数之间不能直接进行小于比较操作。

解决这个问题的方法是将用户输入的字符串转换为整数,在比较时使用整数进行比较。要修正代码,可以将以下两行代码更改如下:

  1. temp = int(input("请用户输入一个1到10的数字:"))
复制代码


以及

  1. if temp < answer:
复制代码


这样,首先将用户输入的字符串转换为整数,然后才进行大小比较。

修正后的代码如下:

  1. import random

  2. answer = random.randint(1, 10)
  3. opportunity = 0

  4. while opportunity < 3:
  5.     temp = int(input("请用户输入一个1到10的数字:"))
  6.    
  7.     if temp == answer:
  8.         print("恭喜你答对了")
  9.         break
  10.     else:
  11.         if temp < answer:
  12.             print("小了")
  13.         else:
  14.             print("大了")
  15.         opportunity += 1

  16. print("游戏结束!!!")
复制代码


希望这能够解决您的问题!如果还有其他疑问,请随时提问。
如果问题已经解决,请设置最佳答案
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-10-1 03:55

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表