0
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?

2
  • 3
    Tried it, does print "doing task2": eval.in/961305 Commented Feb 22, 2018 at 21:42
  • The expression (left and right) will return 0 when one of the variables equal 0. And will always return right value in any other case. Commented Feb 22, 2018 at 22:07

4 Answers 4

2

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'
Sign up to request clarification or add additional context in comments.

Comments

0

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')

Comments

0
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

Comments

0

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))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.