繁体   English   中英

Python数学代码大于和小于不起作用

[英]Python math code greater than and less than not working

import numpy as np
import random
i = random.randint(1,100)
if i > 0 and i <16:
    print ("Broken")
else if i > 16 and i > 100
    print ("Not broken")

我正在尝试使数字在1到15之间,但球拍坏了,但如果是16-100,则拍子没有坏。 它说这是python中的无效语法。 为什么语法无效?

您有2个SyntaxErrors:

还有一个逻辑错误:

  • i > 100永远不可能是True

然后,您也不需要and在这里,您可以使用:

import random
i = random.randint(1,100)
if i < 16:
    print ("Broken")
else:
    print ("Not broken")

还有i > 0 and i < 16的缩写:

if 0 < i < 16:
    print ("Broken")
elif 16 < i <= 100:  # compare to "<= 100" instead of "> 100"
    print ("Not broken")

您似乎正在尝试将嵌套的if语句“折叠”为C风格的包含if语句:

if (i > 0 && i < 16)
    printf("Broken\n");
else
    if (i > 16 && i < 100)
        printf("Not broken\n");

由于空格不重要,因此上述内容等效于

if (i > 0 && i < 16)
    printf("Broken\n");
else if (i > 16 && i < 100)
    printf("Not broken\n");

给出else if子句的错觉。


在Python中,缩进非常重要,因此您不能像在C中那样使用相同的技巧。相反,Python具有显式的elif子句,可用于在单个if语句中检查多个条件。

if i > 0 and i < 16:
    print("Broken")
elif i > 16 and i < 100:
    print("Not broken")

这在语义上等同于

if i > 0 and i < 16:
    print("Broken")
else:
    if i > 16 and i < 100:
        print("Not broken")

但看起来更好。

在Python中,您可以使用elif代替else if 您还需要在else if行的末尾添加一个冒号。

它应该是:

elif i > 16 and i > 100:

elif并以“:”结尾

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM