[英]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")
I am trying to make it if the number is between 1 to 15 the racquet is broken but if it is 16-100 it is not broken. 我正在尝试使数字在1到15之间,但球拍坏了,但如果是16-100,则拍子没有坏。 It says it is invalid syntax in python.
它说这是python中的无效语法。 Why is it invalid syntax?
为什么语法无效?
You've got 2 SyntaxErrors: 您有2个SyntaxErrors:
There is no else if
in Python, just elif
在Python中没有
else if
,只有elif
You need a :
after the conditions . 您需要一个
:
条件之后 。
And a logical mistake: 还有一个逻辑错误:
i > 100
can never be True
. i > 100
永远不可能是True
。 Then you also don't need and
here, you could just use: 然后,您也不需要
and
在这里,您可以使用:
import random
i = random.randint(1,100)
if i < 16:
print ("Broken")
else:
print ("Not broken")
There is also the shortened version of i > 0 and i < 16
: 还有
i > 0 and i < 16
的缩写:
if 0 < i < 16:
print ("Broken")
elif 16 < i <= 100: # compare to "<= 100" instead of "> 100"
print ("Not broken")
You appear to be trying to "fold" a nested if
statement into its containing if
statement, C-style: 您似乎正在尝试将嵌套的
if
语句“折叠”为C风格的包含if
语句:
if (i > 0 && i < 16)
printf("Broken\n");
else
if (i > 16 && i < 100)
printf("Not broken\n");
Because the whitespace isn't significant, the above is equivalent to 由于空格不重要,因此上述内容等效于
if (i > 0 && i < 16)
printf("Broken\n");
else if (i > 16 && i < 100)
printf("Not broken\n");
giving the illusion of an else if
clause. 给出
else if
子句的错觉。
In Python, indentation is significant, so you can't pull the same trick as in C. Instead, Python has an explicit elif
clause that you can use to check multiple conditions in a single if
statement. 在Python中,缩进非常重要,因此您不能像在C中那样使用相同的技巧。相反,Python具有显式的
elif
子句,可用于在单个if
语句中检查多个条件。
if i > 0 and i < 16:
print("Broken")
elif i > 16 and i < 100:
print("Not broken")
This is semantically equivalent to 这在语义上等同于
if i > 0 and i < 16:
print("Broken")
else:
if i > 16 and i < 100:
print("Not broken")
but nicer looking. 但看起来更好。
In Python, you use elif
instead of else if
. 在Python中,您可以使用
elif
代替else if
。 You also need a colon at the end of your else if line. 您还需要在else if行的末尾添加一个冒号。
It should be: 它应该是:
elif i > 16 and i > 100:
elif and with ":" in the end elif并以“:”结尾
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.