我完全不同意接受的答案。是的,indention在Python中非常重要,但要声明if-else必须始终看起来像这种格式有点过分。
Python允许您使用单行(甚至是多行),只要您不需要在if,elif或else的主体中执行任何花哨的操作。
这里有些例子:
choice = 1
# if with one-liner
if choice == 1: print('This is choice 1')
# if-else with one-liners
if choice == 1: print('This is choice 1')
else: print('This is a choice other than 1')
# if-else if with one-liners
if choice == 1: print('This is choice 1')
elif choice == 2: print('This is choice 2')
# if-else if-else with one-liners
if choice == 1: print('This is choice 1')
elif choice == 2: print('This is choice 2')
else: print('This is a choice other than 1 and 2')
# Multiple simple statements on a single line have to be separated by a semicolumn (;) except for the last one on the line
if choice == 1: print('First statement'); print('Second statement'); print('Third statement')通常不建议在一行中包含太多语句,因为这样你就失去了Python的一个重要特性 - 代码的可读性。
另请注意,上述示例也可以轻松应用于for和while。如果你使用三元条件运算符,你可以更进一步做一些单行if块的疯狂嵌套。
以下是操作员通常的样子:
flag = True
print('Flag is set to %s' % ('AWESOME' if True else 'BORING'))这样做基本上是创建一个简单的if-else语句。如果您需要更多分支(但不是复杂的分支),您可以使用其中一个单行器嵌入它。
希望这能澄清一下情况,允许和不允许的情况。 ;)