简体   繁体   English

Python:为什么我运行代码时字符串不返回或不打印

[英]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. 我正在尝试获取if表达式来运行代码并根据原始输入返回任一字符串。 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 ). 您应该使用raw_input()而不是input()否则Python会将用户输入解释为变量(这就是为什么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. 此外,您不应将raw_input()用作默认参数值,因为每当Python加载模块时都会对raw_input()进行评估。

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. 尽管我不得不说,但是尚不清楚上述功能的目的是什么,因为Question现在既可以是一个问题,也可以是用户的答案。 How about passing in the question as a string and assigning the result to Answer ? 将问题作为字符串传递并将结果分配给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: 最后,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!"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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