Python-elif语法错误-这有什么问题?
我正在尝试编写一个函数,它接受一个列表,如果它按该顺序包含数字0,0,7,则返回true。当我运行此代码时:Python-elif语法错误-这有什么问题?,python,function,debugging,statements,Python,Function,Debugging,Statements,我正在尝试编写一个函数,它接受一个列表,如果它按该顺序包含数字0,0,7,则返回true。当我运行此代码时: def prob11(abc): if 7 and 0 and 0 not in abc: return False x = abc.index(0) elif 7 and 0 and 0 in abc and abc[x + 1] == 0 and abc[x + 2] == 7: return True else:
def prob11(abc):
if 7 and 0 and 0 not in abc:
return False
x = abc.index(0)
elif 7 and 0 and 0 in abc and abc[x + 1] == 0 and abc[x + 2] == 7:
return True
else:
return False
我得到这个错误:
File "<ipython-input-12-e2879221a9bf>", line 5
elif 7 and 0 and 0 in abc and abc[x + 1] == 0 and abc[x + 2] == 7:
^
SyntaxError: invalid syntax
文件“”,第5行
在abc和abc[x+1]==0和abc[x+2]==7中的elif 7和0以及0:
^
SyntaxError:无效语法
我的elif声明有什么问题吗?你可以试试这个,希望对你有帮助
def prob11(abc):
if 7 in abc and abc.count(0) >= 2:
return True
else:
return False
print(prob11([0, 0, 7]))
# print True
print(prob11([0, 0, 6]))
#print False
我不确定这是否是解决您问题的最佳/快速方法,但这对我很有效:
def checker(abc):
if 7 or 0 in abc:
print('yes1')
if all(x in abc for x in [0, 0, 7]):
print('yes2')
if sorted(abc)==abc:
print('yes3')
abc=[0,0,7]
v=checker(abc)
您的代码不起作用,因为和和中的不会以这种方式起作用。我不知道为什么。
因此,您需要使用all
函数 我建议你看一看,在if-else中不能有x=abc.index(0)
。如果elif else
中的所有语句也处于下一缩进级别,7、0和0不在abc中
并不意味着你所期望的意思。如果7、0和0不在abc中:
总是False
-请阅读副本并重新检查关于if/elif/else的文档。@PatrickArtner,而代码似乎有问题(),你已经链接为副本(虽然我不完全清楚OP打算如何让逻辑工作),但它没有解决被问到的语法问题。我投票决定重新打开。下一个问题您将遇到: