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!"
我试图获取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
>>>
答案 0 :(得分:7)
您应该使用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!"
虽然,我不得不说,上述功能的目的并不完全清楚,因为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!"
最后,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!"