【问题标题】:"Not Equal" != into Python 3 not working [duplicate]“不等于”!=进入Python 3不起作用[重复]
【发布时间】:2018-02-03 04:20:59
【问题描述】:

我正在尝试将代码从 Python 2.7.10 切换到 Python 3,但有些东西不起作用。我最近才被介绍给 Python。

choice = 2
while choice != 1 and choice != 0:
    choice = input("Hello, no.")
    if choice != 1 and choice != 0:
       print("Not a good code.")

如何将“!=”更改为 Python 3 可以理解的内容?当我输入 1 或 0 时,它给了我“你好,不”的无效打印。

【问题讨论】:

  • 首先,学会缩进你的代码。其次,Python3 中的input 返回一个字符串。在比较之前,您必须将其转换为 int。第三,您可能会发现此文档很有用:docs.python.org/3/howto/pyporting.html
  • @DYZ:这看起来与这个问题相反......
  • choices = 2choice=str(choices) whilechoice != '1' 和choice != '0':choice = input("Hello, no.") ifchoice != '1'和选择!='0':打印(“不是一个好的代码。”)

标签: python python-3.x


【解决方案1】:

input 函数将用户输入作为字符串返回。您可以使用intfloat 方法将其转换为数字:

choice = 2
while choice != 1 and choice != 0:
    choice = input("Hello, no.")
    choice = int(choice)
    if choice != 1 and choice != 0:
       print("Not a good code.")

【讨论】:

    【解决方案2】:

    Python 3 中的input 等价于Python 2 的raw_input;它读取一个字符串,它不会尝试eval 它。这是因为eval 的用户输入本质上是不安全的。

    如果您想在 Python 3 中安全地执行此操作,您可以将对 input 的调用封装在 int 中以转换为 int,或在 ast.literal_eval 中解释任意 Python 文字,而无需将自己开放给任意代码执行。

    import ast
    
    choice = 2
    while choice != 1 and choice != 0:
        choice = ast.literal_eval(input("Hello, no."))
        if choice != 1 and choice != 0:
           print("Not a good code.")
    

    【讨论】:

      猜你喜欢
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      相关资源
      最近更新 更多