python缩进块是什么_python中IF-ELSE块的缩进

博客讨论了Python中if-else语句的使用,指出虽然Python强调代码可读性,但也允许在一行内编写简单if-else结构。作者提供了多个单行if-else的例子,并强调过多的一行语句可能牺牲代码的可读性。同时,提到了三元条件运算符的使用,以及在保持代码简洁与可读性之间的平衡。
摘要由CSDN通过智能技术生成

我完全不同意接受的答案。是的,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语句。如果您需要更多分支(但不是复杂的分支),您可以使用其中一个单行器嵌入它。

希望这能澄清一下情况,允许和不允许的情况。 ;)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值