简体   繁体   中英

Python: why doesn't my string return or print when I run my code

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
>>> 

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!"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM