【发布时间】:2020-03-21 18:43:06
【问题描述】:
我只是在编写一个简单的 if/elif/else 语句,但在使用 else 而不是 elif 时,我不断收到语法错误。它们在完全相同的地方使用。这里有两个例子:
fruit = 'banana'
if 'e' in fruit:
print('found it')
elif 'b' in fruit:
print('found it')
fruit = 'banana'
if 'e' in fruit:
print('found it')
else 'b' in fruit:
print('found it')
elif 代码运行没有问题,而使用 else 的代码会产生语法错误:
line 4
else 'b' in fruit:
^
SyntaxError: invalid syntax
【问题讨论】:
-
因为
else不能包含逻辑条件。 -
你能澄清你的问题吗?是什么让您认为
else可以像elif一样使用? -
这能回答你的问题吗? syntax error in if...else condition
标签: python if-statement