我一直在使用《Python 绝对初学者指南》一书学习如何使用 Python 编程。我遇到的问题是,当使用
eclipse-pydev
时,它不允许我使用 if
语句。这是我写的代码...
name = input("What is your name? ")
print(name)
print("Hello" name )
结果是
What is your name? caleb
Traceback (most recent call last):
File "/Users/calebmatthias/Document/workspace/de.vogella.python.first/simpprogram.py", line 6, in <module>
name = input("What is your name? ")
File "/Users/calebmatthias/Desktop/eclipse 2/plugins/org.python.pydev_2.2.3.2011100616/PySrc/pydev_sitecustomize/sitecustomize.py", line 210, in input
return eval(raw_input(prompt))
File "<string>", line 1, in <module>
NameError: name 'caleb' is not defined
当我做我的
if
声明时
name = input("What is your name? ")
if name == ("Caleb"):
print(" Hello Bud!")
结果是
What is your name? Caleb
Traceback (most recent call last):
File "/Users/calebmatthias/Document/workspace/de.vogella.python.first/simpprogram.py", line 6, in <module>
name = input("What is your name? ")
File "/Users/calebmatthias/Desktop/eclipse 2/plugins/org.python.pydev_2.2.3.2011100616/PySrc/pydev_sitecustomize/sitecustomize.py", line 210, in input
return eval(raw_input(prompt))
File "<string>", line 1, in <module>
NameError: name 'Caleb' is not defined
原因是您正在使用
input
函数,该函数期望用户输入一个可以计算为 python 表达式的字符串。尝试将其更改为 raw_input
,它不会尝试评估,而是给你一个原始字符串。
另外,尝试只执行打印语句,例如:print "Hello", name
您在第一个示例中缺少逗号分隔符。
>>> help(input)
input([prompt]) -> value
Equivalent to eval(raw_input(prompt)).
使用
raw_input
。