Python 3.x 随机数与算子

Python 3.x 随机数与算子,python-3.x,logical-operators,Python 3.x,Logical Operators,我不明白为什么下面的代码不能正常工作。如果变量a和b均

我不明白为什么下面的代码不能正常工作。如果变量a和b均<0,则应打印两个数字均为负数,否则显示最后一条消息。但它就是不起作用所以,我做错了什么?请帮忙

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!")
随机导入
尽管如此:
输入()
a=随机的随机数(-9,9)
b=随机随机随机数(-9,9)
印刷品(a、b)
如果a和b<0:
打印(“2个负数:”,a,b)
其他:
打印(“一个或两个数字都是正数!”)

我在Python3.4上运行它。

您只是在评估
a
,而不是它与
0
的关系:

if a < 0 and b < 0:
如果a<0且b<0:
这是:

a and b < 0:

计算两个操作数将解决此问题。在这里,两个操作数都是表达式,其结果为true或false,因此如果两者都为true;你会得到你想要的结果

if ((a < 0) and (b < 0)):
if((a<0)和(b<0)):

我想您对运营商如何分发有点困惑

当你有

if a and b < 0
如果a和b<0
这并不意味着

if (both a and b) < 0
if(a和b)<0
而是

if (a) and (b < 0)
if(a)和(b<0)
这相当于

if (a != 0) and (b < 0)
如果(a!=0)和(b<0)
因为“所有类型的数字零…计算结果为false”(请参阅)


相反,你想要

if a < 0 and b < 0
如果a<0且b<0

这将告诉您
a
b
是否都小于零。

Hi可能重复,欢迎使用stackoverflow。虽然这可能对问题有帮助,但答案并没有遵循此网站的预期格式。我建议你提供更多信息,说明为什么这个答案是有用的。
if (a != 0) and (b < 0)
if a < 0 and b < 0