0

i dont understand why the code bellow doesnt work properly. If both variables a and b < 0 it should print that both numbers are negative,else the last message. But it just dont work so, what am i doing wrong? please help!

import random
while True:
    input()
    a=random.randint(-9,9)
    b=random.randint(-9,9)
    print(a,b)
    if a and b < 0:
        print("2 negative numbers:",a,b)
    else:
        print("one or both of the numbers are positive!")

I'm running this on python 3.4.

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
  • possible duplicate of [How do I test one variable against multiple values?](http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values) – jonrsharpe May 24 '15 at 10:02

4 Answers4

1

Evaluating Both Operands will resolve the issue. Here both Operands are expressions which results in true or false, so if both result in true; you will get your required result.

if ((a < 0) and (b < 0)):
MMaazQ
  • 43
  • 7
  • 2
    Hi and welcome to stackoverflow. Although this may be helpful for the question, the answer is not following the expected format for this site. I would recommend you to provide more information on why this answer is helpful. – Wtower May 24 '15 at 10:37
1

I think you're a little confused about how operators distribute.

When you have

if a and b < 0

it doesn't mean

if (both a and b) < 0

but instead

if (a) and (b < 0)

which is equivalent to

if (a != 0) and (b < 0)

since "numeric zero of all types ... evaluates to false" (see the reference on booleans on docs.python.org)


Instead, you want

if a < 0 and b < 0

which will tell you if both a and b are less than zero.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
0

You are evaluating just a, not it's relation to 0:

if a < 0 and b < 0:
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

This:

a and b < 0:

Is equivalent to this:

(a) and (b < 0):

(a) is False when a equals 0 and True otherwise. Therefore, due to short-circuiting b < 0 isn't even evaluated.

As a fix you may use all method:

all(i < 0 for i in (a, b))
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93