Python Can';t验证形状是否为三角形
当我插入“2”、“2”和“2”时,一切正常,但当我输入“3”、“4”和“5”时,我得到:Python Can';t验证形状是否为三角形,python,python-2.7,Python,Python 2.7,当我插入“2”、“2”和“2”时,一切正常,但当我输入“3”、“4”和“5”时,我得到: “形状不是三角形。”。你能帮我找到问题吗?(我现在看到我可以在另一篇文章中找到解决方案,但我……不知道问题所在)在Python2.7中: raw_input返回一个str值。使用input()或将raw\u input()类型转换为int: from math import sqrt a = raw_input("First length: ") b = raw_input("Second length:
“形状不是三角形。”。你能帮我找到问题吗?(我现在看到我可以在另一篇文章中找到解决方案,但我……不知道问题所在)在Python2.7中:
raw_input
返回一个str
值。使用input()
或将raw\u input()
类型转换为int
:
from math import sqrt
a = raw_input("First length: ")
b = raw_input("Second length: ")
c = raw_input("Third length: ")
if a >0 and b >0 and c >0 and a + b > c and a + c > b and b + c > a :
if a == b == c:
print "Equilateral triangle."
elif a == b and a != c and b != c:
print "Isosceles triangle."
elif (a==sqrt(b*b+c*c) or b==sqrt(a*a+c*c) or c==sqrt(a*a+b*b)):
print "Right triangle."
else:
print "Simple triangle."
else:
print "The shape is not a triangle."
Python 3中的
只有input()
注意:根据:
input('Something…')
相当于eval(原始输入('Something…'))
由于安全原因,我们不应该在代码中使用eval
。阅读:首先,你搞乱了毕达哥拉斯定理:)raw\u输入
返回字符串,而不是数字。您需要int(原始输入(“第一个长度”)
或float(原始输入(“第一个长度”))
。它适用于相同的输入,因为您正在比较相同的字符串。一旦这些数字的字符串表示形式发生更改,elif
子句中没有一个是真的b!=c
检查是否冗余;如果前面的两个比较是真的,那么它一定是真的。@chepner哦,是的。我没有意识到。不要建议输入
。Python3抛弃它是有原因的。但用户提到标签为Python2.7
@MoinuddinQuadri true,并且input
存在。但是,它在Python2.7中对输入调用eval()
,并且eval
不安全;如果是Python3,您将别无选择<代码>输入
不应使用;使用raw_input
,并将值转换为您想要的类型,而不是让Python猜测,也许做的比您想要的更多。我同意你们两人的看法。添加了关于为什么不应使用输入的注释
int(raw_input("First length: "))