python - 如何正确使用反斜杠在 if 语句中续行?

标签 python

例如D、如果sum_p不为零。

D = 1/sum_p if sum_p \
    else 0

如果我想返回值怎么办?我应该怎么做:

return 1/sum_p if sum_p \
else 0

或者直接写

if...
else: return 0

最佳答案

如果你想做单条语句条件返回,使用:

return 1 / sum_p if sum_p else 0

这不是if 语句。这是一个conditional expression .把它想象成

return (this_value if this_condition_is_true else that_value)

return 本身条件之外。

如果该行足够长,您必须将其拆分,在风格上我建议使用普通的 if 语句和两个 return 语句。

一般来说,不要使用 \ 作为行终止符PEP-8建议您始终使用括号:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it. Some examples:

关于python - 如何正确使用反斜杠在 if 语句中续行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10195656/

相关文章:

python - 测量数据帧的负/正偏度

python - PEP8、locals() 和插值

java - 有哪些好的开源程序可以对流行的图像文件类型进行模糊测试?

Python 绘制时间序列并强调其中的一部分

python - postgres 插入规则而不是更新

python - 编程语言翻译器如何工作?

python - 特定 Enum 值的类型注释

python - 为什么python看不到模块?

python - 在 Tensorflow 中对 MNIST 运行测试时出现数据类型转换错误

python - 在 Heroku 上发送 Django 电子邮件