Python 中设置多行 if 语句的样式
Python 中多行 if 语句的推荐样式是使用括号分隔 if 语句。 PEP8 样式指南建议在反斜杠上使用括号,并在布尔值 and
和 or
运算符之后放置换行符。
if ('hi' == 'hi' and
len('hi') == 2 and
2 == 2): # 👈️ 最后一行有额外的缩进
print('success')
# 👇️ 所有条件都在不同的行上
if (
'hi' == 'hi' and
len('hi') == 2 and
2 == 2
):
print('success')
# 👇️ 使用反斜杠续行(pep8 不鼓励)
if 'hi' == 'hi' and \
len('hi') == 2 and \
2 == 2:
print('success')
根据官方 PEP8 样式指南,包装长行的首选方法是在括号、方括号和大括号内使用 Python 的隐含行延续。
该指南不建议使用反斜杠来续行。
该指南还建议在布尔运算符
and
和or
之后放置换行符。
代码示例中的第一个示例使用额外的缩进来区分 if 语句中的条件和 if 块中的代码。
# ✅ GOOD
if ('hi' == 'hi' and
len('hi') == 2 and
2 == 2): # 👈️ 最后一行有额外的缩进
print('success')
这使得我们的代码比对条件和 if
块使用相同级别的缩进更具可读性。
# ⛔️ BAD (same level of indentation for conditions and body of if statement)
if ('hi' == 'hi' and
len('hi') == 2 and
2 == 2):
print('success')
我们还可以将 if
语句中的所有条件移动到单独的行中。
# ✅ GOOD
if (
'hi' == 'hi' and
len('hi') == 2 and
2 == 2
):
print('success')
使用这种方法时,我们不必对条件使用额外的缩进,因为右括号将条件与
if
语句的主体分开。
对于更长的 if 语句,我发现这比前面的示例更容易阅读。
尽管 PEP8
样式指南不鼓励使用反斜杠来续行,但它仍然是一种完全有效的语法。
if 'hi' == 'hi' and \
len('hi') == 2 and \
2 == 2:
print('success')
使用这种方法时,请确保为最后一行条件添加额外的缩进。
如果大家对条件和 if
语句的主体使用相同级别的缩进,则代码将变得难以阅读。
# ⛔️ BAD (same level of indentation for conditions and `if` body)
if 'hi' == 'hi' and \
len('hi') == 2 and \
2 == 2:
print('success')
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。