是否可以在与 if 语句本身相同的行上格式化 'if' 语句的任何部分内容?
Is it ever okay to format any part of the contents of an 'if' statement on the same line as the if statement itself?
我正在为初学者做一些练习 Python,我正在尝试确定正确的格式,如何使您的代码干净快速,以及其他类似的东西。
我不确定的一件事是 if
语句。
以下是我通常做 if
语句的方式:
if something:
do (something)
但我见过有人这样做:
if something: do (something)
我什至看过这个:
if something: do (something)
then do (something else)
我也看到有人用嵌套的 if
语句来做到这一点,其中每个 if
/elif
/else
都有第一行代码与 if/elif/else 本身相同的行。
执行这些其他方法中的任何一种都可以/正确的形式吗?
PEP 8,Python 的开创性风格指南,不鼓励这种行为:
Compound statements (multiple statements on the same line) are generally discouraged.
这样做通常是有效的语法,只要只涉及一行,但它被认为是一种不好的做法。避开它。
我想向您推荐 [=19= 的禅宗],作者 Tim Peters,特别是第 1、3 和 7 项。
$ python
>>> import this
The Zen of Python, by Tim Peters
1) Beautiful is better than ugly.
3) Simple is better than complex.
7) Readability counts.
您 可以 在 Python 中做很多事情,我敢打赌很多人都希望您做不到。我会坚持使用最简单、最容易阅读的代码,以后你会感谢自己的。
这是我习惯的语法:
x = 4
if (x%2) == 0:
print "pair"
else:
print "impair"
您必须使用 "elif"(而不是 "else if")作为其他选择。希望能帮助到你。
我正在为初学者做一些练习 Python,我正在尝试确定正确的格式,如何使您的代码干净快速,以及其他类似的东西。
我不确定的一件事是 if
语句。
以下是我通常做 if
语句的方式:
if something:
do (something)
但我见过有人这样做:
if something: do (something)
我什至看过这个:
if something: do (something)
then do (something else)
我也看到有人用嵌套的 if
语句来做到这一点,其中每个 if
/elif
/else
都有第一行代码与 if/elif/else 本身相同的行。
执行这些其他方法中的任何一种都可以/正确的形式吗?
PEP 8,Python 的开创性风格指南,不鼓励这种行为:
Compound statements (multiple statements on the same line) are generally discouraged.
这样做通常是有效的语法,只要只涉及一行,但它被认为是一种不好的做法。避开它。
我想向您推荐 [=19= 的禅宗],作者 Tim Peters,特别是第 1、3 和 7 项。
$ python
>>> import this
The Zen of Python, by Tim Peters
1) Beautiful is better than ugly.
3) Simple is better than complex.
7) Readability counts.
您 可以 在 Python 中做很多事情,我敢打赌很多人都希望您做不到。我会坚持使用最简单、最容易阅读的代码,以后你会感谢自己的。
这是我习惯的语法:
x = 4
if (x%2) == 0:
print "pair"
else:
print "impair"
您必须使用 "elif"(而不是 "else if")作为其他选择。希望能帮助到你。