unorderable类型:str()> INT()

时间:2016-02-13 03:38:55

标签: python string int

所以我试图制作的程序包含三个输入,等于右,等腰或钝角三角形,当我运行我的代码时,我遇到了这个问题。我已经将int()放在了所有内容之前。我做错了什么?

angle_1 = input("What is the degree of the first angle? ")
angle_2 = input("What is the degree of the second angle? ")
angle_3 = input("What is the degree of the third angle? ")


if int(angle_1 or angle_2 or angle_3) == 90:
    print("This is a right triangle.")
elif int((angle_1 or angle_2 or angle_3) > 90) and int((angle_1 or angle_2 or angle_3) < 180):
    print("This is an obtuse triangle.")
else:
    print("This is an acute triangle.")     

2 个答案:

答案 0 :(得分:0)

if语句中的语法不明确。我会列出角度名称,然后循环遍历它们。

angle_1 = input("What is the degree of the first angle? ")
angle_2 = input("What is the degree of the second angle? ")
angle_3 = input("What is the degree of the third angle? ")

# This will be looped through
angle_list=[angle_1, angle_2, angle_3] # This will be looped through

for angle in angle_list: # Goes through each inputted angle. 
    if angle == 90:
        print 'This triangle is right.'
        break
    elif angle > 90:
        print 'This triangle is obtuse.'
        break
    else:
        print 'This is an acute triangle.'
        break

为了将来参考,您可能希望在使用新概念时直接参考文档。 or是一个逻辑运算符,而不是布尔值。

答案 1 :(得分:0)

您的第一个问题是您需要将输入从字符串转换为int。名义上,这是由val = int(intput('something: '))完成的,但由于用户习惯输入垃圾,因此您需要在转换时捕获错误。这对函数来说是一个很好的角色。

你的第二个问题是or运算符,正如几个地方所描述的那样。考虑到解决方案,您有几个要比较的值,因此将它们放入列表中是很自然的。一旦你完成了这个,python就会有一些技巧和有用的功能,可以让你提出这些值的问题。

把它们放在一起,你就得到了

def get_input(prompt, cast_to=str):
    while True:
        try:
            val = input(prompt)
            return cast_to(val)
        except ValueError:
           print("'{}' is in valid, try againr".format(val))

angle_1 = get_input("What is the degree of the first angle? ", int)
angle_2 = get_input("What is the degree of the second angle? ", int)
angle_3 = get_input("What is the degree of the thrid angle? ", int)

angles = [angle_1, angle_2, angle_3]

if sum(angles) != 180:
    print("We are sticking with Euclidean geometry pal")
elif 90 in angles:
    print("This is a right triangle.")
elif max(angles) > 90:
    print("This is an obtuse triangle.")
else:
    print("This is an acute triangle.")