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!"
I am trying to get the if expression to run the code and return either string based on the raw input. Everytime I run it, the question prompts but then when I attempt to input 'yes or no' it gives me this error:
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
>>>
1 Answer 1
You should use raw_input() instead of input() otherwise Python interprets the user input as variables (that's why you're getting name 'yes' is not defined).
Furthermore, you shouldn't use raw_input() as default parameter value as this is evaluated whenever Python loads the module.
Consider the following:
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!"
Although, I have to say, it's not entirely clear what purpose the above function has because Question can now be both a question and the user's answer. How about passing in the question as a string and assigning the result to 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!"
Lastly, variable names in Python are written without capitals at the beginning so the code would become:
def the_flying_circus(question):
answer = raw_input(question)
if answer == 'yes':
print "That's great!"
elif answer == 'no':
print "That's too bad!"
4 Comments
if not Question is preferred idiom to if Question is Nonequestion to be PEP-8 compliantif not Question and if Question is None are not equivalent so you can't always use either of them. Also, I adapted the code as written in the question - it's not always useful to teach people about additional stuff, such as PEP8, when you're starting to learn Python.
raw_inputin the first line of the code to theinputin the traceback.