例如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/