【问题标题】:Does Python input need to be surrounded by quotes?Python 输入是否需要用引号括起来?
【发布时间】:2021-10-05 08:19:29
【问题描述】:

这应该很简单,但我找不到解释。这是我的代码:

 car = input("What kind of car would you like? ")
    print("\nLet me see if I can find a {}".format(car))

终端会提示输入汽车类型。

我输入:福特

我收到此错误:

What kind of car would you like? Ford
Traceback (most recent call last):
  File "rental_car.py", line 1, in <module>
    car = input("What kind of car would you like? ")
  File "<string>", line 1, in <module>
NameError: name 'Ford' is not defined

如果我输入:“福特” 程序按预期运行。

除了数字之外,Python 是否需要在输入值上加上引号?

感谢您的帮助!

【问题讨论】:

  • 不,可能是编译器问题
  • 谢谢,非常感谢!

标签: python string input quotes


【解决方案1】:

在 Python 2.x 上,函数 input 会评估用户输入的任何内容。正如文档所述,这相当于eval(raw_input(...))

因此,在 Python 2.x 上,您应该改用 raw_input

或者,为了兼容 Python 2 和 3,您可以使用six.moves.input

【讨论】:

  • raw_input 解决了这个问题,谢谢!
猜你喜欢
  • 2021-06-06
  • 2018-02-26
  • 2022-11-10
  • 2020-09-07
  • 2010-09-12
  • 1970-01-01
  • 2011-01-26
  • 1970-01-01
相关资源
最近更新 更多