在python中使用多个不相互排斥的Ifs

Kat*_*ugh 4 python if-statement

a=0
while a<30:
    a+=1
    print(a)
    if a%3==0:
        print("This is a multiple of 3.")
    if a%5==0:
        print("This is a multiple of 5.")
    else:
        print("This is not a multiple of 3 or 5.")
Run Code Online (Sandbox Code Playgroud)

我希望这个else语句只在前面的if语句中的NEITHER为真时打印.我不想使用if,elif,else因为变量可能是3和5的倍数.

Jea*_*bre 6

如果其中一个条件匹配,您可以设置一个标志.如果False两个测试后标志仍然存在,则打印后备消息:

a=0
while a<30:
    a+=1
    print(a)
    match = False
    if a%3==0:
        print("This is a multiple of 3.")
        match = True
    if a%5==0:
        print("This is a multiple of 5.")
        match = True
    if not match:
        print("This is not a multiple of 3 or 5.") 
Run Code Online (Sandbox Code Playgroud)

这种技术也避免了不止一次计算3和5的模数.

如果你想添加更多的除数,请避免复制/粘贴,并考虑在循环中进行测试(BTW为什么while在有for和时使用循环range?):

for a in range(1,31):
    print(a)
    match = False
    for i in [3,5]:
        if a%i==0:
            print("This is a multiple of {}.".format(i))
            match = True
    if not match:
        print("This is not a multiple of 3 or 5.")
Run Code Online (Sandbox Code Playgroud)

  • 是! 我打算对此发表评论,但是你打败了我. (3认同)