Python 中是否有任何"unless"像"except"一样工作,但适用于普通代码,而不是异常



我知道有人问关于"除非"作为if notnot in工作,但我想有一个语句引入一个异常的条件语句。例如:

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

在我看来,你的预设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,但更容易阅读:)

将else反过来,先检查是否为10。

If num == 10:
    # in this case do something
elif num >= 0 and num <= 99:
    # then do sth

最新更新