【问题标题】:turning an input into a string into a integer将输入转换为字符串转换为整数
【发布时间】:2016-04-24 22:01:30
【问题描述】:

我正在编写一些通过文本提示(命令行)接收用户输入的代码。此代码的目标是获取用户输入,确保它满足某些要求,然后使用它来编辑其他变量。这是代码,(稍微改变了输入和变量的名称:)

import os

command = 0
cmd = input(">")
command = int(cmd)
if command <= 0:
    print("That number is too low.")
    os.exit(1)
elif command >= 11:
    print("That number is too high.")
    os.exit(1)
else:
example1 = command
example2 = command + example1

但是,当它运行时它声称存在unorderable types: str() &lt;= int()。 由于此代码不起作用,有人可以帮助修复它或告诉我另一种将输入转换为整数的方法吗?我正在使用 Python 3+。

【问题讨论】:

  • 您提供的代码不会/不会发生这种情况。您确定在某处没有 cmd 代替 command 吗?
  • 我确定,但它仍然给我这个错误。然而,它没有给我计算的行号,而是给了我给变量命令它的值的行。 (本例中为第 5 行。)
  • 那么你必须运行一个不同的脚本,否则你修改后没有保存它。
  • 我没有将 else 放入我的实际脚本中。很抱歉造成混乱。
  • else 没有区别,另外一个注释没有os.exit,你的意思是os._exit

标签: python-3.x integer


【解决方案1】:
import os

command = int(input(">"))

if command <= 0:
    print("That number is too low.")
    os.exit(1)
elif command >= 11:
    print("That number is too high.")
    os.exit(1)
else:
    example1 = command
    example2 = command + example1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 2012-02-21
    • 2010-12-31
    相关资源
    最近更新 更多