Python 中是否有任何 "unless" 像 "except" 一样工作但对于正常代码,而不是异常
is there any "unless" in Python that works like "except" but for normal code, not for exceptions
我知道有人问过作为 if not
或 not in
工作的 "unless",但我想要一个向条件语句引入异常的语句.例如:
if num >= 0 and num <= 99:
# then do sth (except the following line)
unless num = 10:
# in this case do something else
它比写作更清晰直观:
if (num >= 0 and num <= 9) or (num >= 11 and num <= 99):
# then do sth (except the following line)
elif num = 10:
# in this case do something else
if not 语句的作用不同...
注意:我实际上是新手,所以请多多包涵
一个普通的 if 可以做到这一点,如果你重新排序子句:
if num == 10:
# do the num = 10 thing
elif 0 <= num <= 99:
# do something else
反转 else 并首先检查 10。
If num == 10:
# in this case do something
elif num >= 0 and num <= 99:
# then do sth
你的前缀 unless
在我看来会导致非常不直观的代码,当有一个 if
语句时,我希望如果整个条件成立,如果有一种更改它的方法,以便您需要找到块的末尾以查看是否有一些单独的案例,这在阅读代码时会非常令人沮丧。
基本上你对 运行 第一个感兴趣,当 num != 10
是额外条件之一时,所以只需使用:
if 0<=num <= 99 and num!=10:
#statement here
elif num == 10:
#other statement.
另请注意 0 <= num <= 99
本质上等同于 0 <= num and num <= 99
但更易于阅读 :)
我知道有人问过作为 if not
或 not in
工作的 "unless",但我想要一个向条件语句引入异常的语句.例如:
if num >= 0 and num <= 99:
# then do sth (except the following line)
unless num = 10:
# in this case do something else
它比写作更清晰直观:
if (num >= 0 and num <= 9) or (num >= 11 and num <= 99):
# then do sth (except the following line)
elif num = 10:
# in this case do something else
if not 语句的作用不同...
注意:我实际上是新手,所以请多多包涵
一个普通的 if 可以做到这一点,如果你重新排序子句:
if num == 10:
# do the num = 10 thing
elif 0 <= num <= 99:
# do something else
反转 else 并首先检查 10。
If num == 10:
# in this case do something
elif num >= 0 and num <= 99:
# then do sth
你的前缀 unless
在我看来会导致非常不直观的代码,当有一个 if
语句时,我希望如果整个条件成立,如果有一种更改它的方法,以便您需要找到块的末尾以查看是否有一些单独的案例,这在阅读代码时会非常令人沮丧。
基本上你对 运行 第一个感兴趣,当 num != 10
是额外条件之一时,所以只需使用:
if 0<=num <= 99 and num!=10:
#statement here
elif num == 10:
#other statement.
另请注意 0 <= num <= 99
本质上等同于 0 <= num and num <= 99
但更易于阅读 :)