这个程序有什么问题?第4行语法错误。为什么?

时间:2013-10-31 16:02:27

标签: loops python-2.7 if-statement functional-programming

def shut_down(s):
    """develop shut down response on each condition"""
s = None   
if s.lower = "yes" or "Yes":
    print "Shutting down..."

elif s == "No" or "no" :
    print "Shutdown aborted!"

else:
    print "Sorry, I didn't understand you."
shut_down("Yes")

3 个答案:

答案 0 :(得分:1)

错误是您在比较运算符

的位置使用赋值运算符

=代替==而且您没有正确使用lower功能

lower更改为lower()

所以将此行if s.lower = "yes" or "Yes":更改为

if s.lower() == "yes" or "Yes":

答案 1 :(得分:0)

我会说缩进。由于python没有打开和关闭键,缩进是识别代码块的唯一方法。

这是一种非常有趣的方法,因为它迫使开发人员正确地组织和缩进代码。

答案 2 :(得分:0)

参见代码中的评论:

第一个问题:无论您使用s传递给shut_down函数,由于None,它会立即变为s=None,因此请删除该行。

第二个问题:等于运算符的正确语法是== not = s.lower == "yes" or "Yes":lower也是函数,因此您需要将其称为s.lower()。话虽这么说,这对你的问题不是一个正确的方法,而是试试这个,这有点像pythonic:

if s in ['yes', 'Yes', 'y', 'Y']: 

elif语句同样如此

if s in ['no', 'No', 'n', 'N']:

代码:

def shut_down(s):
    """develop shut down response on each condition"""
    s = None  # first problem 
    if s.lower = "yes" or "Yes": # second problem
         print "Shutting down..."

    elif s == "No" or "no" :
         print "Shutdown aborted!"

    else:
         print "Sorry, I didn't understand you."

shut_down("Yes")