Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 416
meteor23 Avatar asked Nov 30 '22 14:11

meteor23


2 Answers

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"
like image 160
francisco sollima Avatar answered Dec 03 '22 05:12

francisco sollima


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")
like image 39
NiziL Avatar answered Dec 03 '22 04:12

NiziL