python 中块的编码实践

Coding practice for blocks in python

是一种不好的做法吗
num1=10
num2=10
if num2!=0: print(num1/num2)
else: print("Cannot divide by zero")

而不是

num1=10
num2=10
if(num2!=0):
    print(num1/num2)
else:
    print("Cannot divide by zero")

个人比较喜欢前者。您的观点有参考资料吗?

是也不是。根据 the official style guide,应该写成:

num1 = 10 # note whitespace
num2 = 10
if num2 != 0:  # note absence of unnecessary parentheses
    print(num1/num2)
else:
    print("Cannot divide by zero")

我猜你问的具体事情的相关引述:

Compound statements (multiple statements on the same line) are generally discouraged.

然而还有其他风格指南,最重要的是一致性

你会参考 Python style guide;以下条目适用:

Compound statements (multiple statements on the same line) are generally discouraged.

Yes:

if foo == 'blah':
    do_blah_thing()
do_one()
do_two()
do_three()

Rather not:

if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()

While sometimes it's okay to put an if/for/while with a small body on the same line, never do this for multi-clause statements. Also avoid folding such long lines!

Rather not:

if foo == 'blah': do_blah_thing()
for x in lst: total += x
while t < 10: t = delay()

Definitely not:

if foo == 'blah': do_blah_thing()
else: do_non_blah_thing()

try: something()
finally: cleanup()

do_one(); do_two(); do_three(long, argument,
                             list, like, this)

if foo == 'blah': one(); two(); three()

您也不应在条件周围使用括号,而应在运算符周围放置空格。

在你的情况下,在 Python 你也会使用异常处理而不是测试(请求原谅,而不是许可):

num1 = 10
num2 = 10
try:
    print(num1 / num2)
except ZeroDisionError:
    print("Cannot divide by zero")

当if/else子句后只有一个语句时,推荐使用第一个选项。同样,它实际上取决于编码风格。第一种风格也经常用于三元运算符/值操作。 Link https://docs.python.org/2/tutorial/controlflow.html 对你有用。