pythonuser123
pythonuser123

Reputation: 15

Confused with logic of my if-statement

right = 0 
left = 0
if(left > right or (left and right) == 0):
    print 'doing task 1'
else:
    print 'doing task2'

for some reason no matter what value I give right or left (for example, if i set right to be 10 and left to be 2)... it always does the "doing task 1" condition.....does anybody know why?

Upvotes: 0

Views: 76

Answers (4)

greybeard
greybeard

Reputation: 2536

you probably want

if right < left or 0 == left and 0 == right:
    print('doing task 1')
else:
    print('doing task 2')

which can be written as

print('doing task %d'
      % (1 if right < left or 0 == left and 0 == right else 2))

Upvotes: 0

sacuL
sacuL

Reputation: 51425

This should do the trick; you had some issues in your if conditions, that's it

if((left > right) or (left == 0 and right==0)):
    print('doing task 1')
else:
    print('doing task2')

Upvotes: 0

Orhan Solak
Orhan Solak

Reputation: 809

I recommend you to use elif function

right = 0
left = 0
if(left > right):
    print 'doing task 1'
elif left ==0 and right == 0:
    print 'doing task 1'    
else:
    print 'doing task2'

Upvotes: 2

ivan7707
ivan7707

Reputation: 1156

right = 2
left = 1
if(left > right or (right == 0 and left == 0)):
    print 'doing task 1'
else:
    print 'doing task2'

I assume you meant to have task 1 show up if either left is greater than right, OR both of right and left are equal to zero.

If you do this

(left and right) == 0

it is doing a boolean comparison, instead of comparing each of left and right to zero.

see boolean operations in the python docs:

section 5.2 as of the time of writing

Upvotes: 0

Related Questions