Python输入错误

3 python input

我在Mac OSX 10.9.5m上运行python 2.7.10并且它无法运行.这是代码:

# YourName.py
name = input("What is your name?\n")
print("Hi, ", name)
Run Code Online (Sandbox Code Playgroud)

这是错误:

Python 2.7.10 (v2.7.10:15c95b7d81dc, May 23 2015, 09:33:12) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
What is your name?
Ella
Traceback (most recent call last):
  File "/Users/CentCom/Downloads/code/ch01/YourName.py", line 2, in <module>
    name = input("What is your name?\n")
  File "<string>", line 1, in <module>
NameError: name 'Ella' is not defined
>>> 
Run Code Online (Sandbox Code Playgroud)

Dav*_*ens 5

raw_input在python 2.7.1中使用:

name = raw_input("What is your name?\n")
Run Code Online (Sandbox Code Playgroud)

否则你必须依赖用户足够熟悉输入带引号的字符串.喜欢"David",或输入尝试评估名称(变量/对象/等),如果范围内没有这样的名称,你将得到错误.

或者,使用异常处理:

name = input("What is your name?\n")
try:
    print("Hi, ", name)
except NameError, e:
    print("Please enclose your input with quotes")
Run Code Online (Sandbox Code Playgroud)

  • @ppperry OP没有使用Python 3 (3认同)