【问题标题】:Same output every time module is run [duplicate]每次运行模块时输出相同[重复]
【发布时间】:2022-08-04 22:29:30
【问题描述】:
num=input(\"Enter number: \")
if num >=\"0\" and num <=\"9\":
    print(\"Number consists of a single digit\")
elif num >=\"10\" and num <=\"99\":
    print(\"Number consists of double digits\")
elif num >=\"100\" and num <=\"999\":
    print(\"Number consists of triple digits\")
else:
    print(\"Number consists of more than 3 digits\")

每次运行它时,我都会不断收到“数字由一个数字组成”。我尝试将数据类型从 str 更改为 int,但随后我得到 \"TypeError: \'>\' not supported 在 \'int\' 和 \'str\'\" 的实例之间 - 我不明白这是什么这意味着什么?所以我回到原来的答案,但没有看到任何错误。我该如何解决?

  • 这是因为您使用的是字符串而不是整数。您想用 (10, 3, 1) 替换所有数字实例 (\"10\", \"3\", \"1\") - 不带引号。除此之外,您还想投掷你的 num 变量转换成一个整数(因为它返回一个字符串)。所以改为int(input(...))
  • 你需要在input()的结果上调用int(),然后你需要进行比较整数。例如,第一个比较应该是if num &gt;= 0 and num &lt;= 9:

标签: python


【解决方案1】:

Python按字典顺序比较字符串

尝试这个 :

num=int(input("Enter number: "))
if num >=0 and num <=9:
    print("Number consists of a single digit")
elif num >=10 and num <=99:
    print("Number consists of double digits")
elif num >=100 and num <=999:
    print("Number consists of triple digits")
else:
    print("Number consists of more than 3 digits")

【讨论】:

    猜你喜欢
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 2013-12-11
    • 1970-01-01
    相关资源
    最近更新 更多