def the_flying_circus(Question = raw_input("Do you like the Flying Circus?")):
if Question == 'yes':
print "That's great!"
elif Question == 'no':
print "That's too bad!"
Run Code Online (Sandbox Code Playgroud)
我试图获取if表达式来运行代码并返回基于原始输入的字符串.每次我运行它时,问题会提示但是当我尝试输入"是或否"时它会给我这个错误:
Traceback (most recent call last):
File "C:\Users\ftidocreview\Desktop\ex.py", line 1, in <module>
def the_flying_circus(Question = input("Do you like the Flying Circus?")):
File "<string>", line 1, in <module>
NameError: name 'yes' is not defined
>>>
Run Code Online (Sandbox Code Playgroud)
您应该使用raw_input()而不是input()Python将用户输入解释为变量(这就是您获得的原因name 'yes' is not defined).
此外,您不应该使用raw_input()默认参数值,因为每当Python加载模块时都会对此进行求值.
考虑以下:
def the_flying_circus(Question=None):
if Question is None:
Question = raw_input("Do you like the Flying Circus?")
if Question == 'yes':
print "That's great!"
elif Question == 'no':
print "That's too bad!"
Run Code Online (Sandbox Code Playgroud)
虽然,我不得不说,上述功能的目的并不完全清楚,因为Question现在既可以是问题,也可以是用户的答案.如何将问题作为字符串传递并将结果分配给Answer?
def the_flying_circus(Question):
Answer = raw_input(Question)
if Answer == 'yes':
print "That's great!"
elif Answer == 'no':
print "That's too bad!"
Run Code Online (Sandbox Code Playgroud)
最后,Python中的变量名称在开头没有大写,因此代码将成为:
def the_flying_circus(question):
answer = raw_input(question)
if answer == 'yes':
print "That's great!"
elif answer == 'no':
print "That's too bad!"
Run Code Online (Sandbox Code Playgroud)