简体   繁体   中英

checking multiple conditions in python

I have below code:

a = 1
b = 2
c = 3
d = 4
e = 5
if ((a == 1 and
     b == 2 and
     c == 4) or
     (d == 4  and e == 5)):
    print "Yeah, Working"
else:
    print "ooops"

Can be achieved same code easy and best way?

If you want to if condition to be clearer or better looking, you can do it like this:

a = 1
b = 2
c = 3
d = 4
e = 5
if (a, b, c) == (1, 2, 4) or (d, e) == (4, 5):
    print "Yeah, Working"
else:
    print "ooops"

It's a very personal answer, but I like to initalize some boolean before the if statement. I find it more readable (because you can give some meaningful name to your variable), and I'm pretty sure the compiler can easily optimize it.

cond1 = a == 1 and b == 2 and c == 4
cond2 = d == 4 and e == 5
if cond1 or cond2:
    print("Yeah, working")
else:
    print("ooops")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM