python中的if语句是否可以替代重复

时间:2018-07-22 23:44:19

标签: python python-3.x if-statement

这是我的代码,似乎有些重复,但是我想不出一种使它与众不同的方法。 (顺便说一句还可以,但是在我看来有点“不干净”)

while True:
    try:
        num1 = int(input("Type in the first parameter: "))
        num2 = int(input("Type in the second parameter: "))
        num3 = int(input("Type in the third parameter: "))
        break
    except ValueError:
        print("You have to type in a number. ")

while True:
    if num1 > num2 and num1 > num3:
        c = num1
        if c * c == num2 * num2 + num3 * num3:
            print("Your triangle is a pythagorean triangle")
        else: 
            print("Your triangle isn't a pythagorean triangle")

    elif num2 > num1 and num2 > num3:                             # c - hypotenuse 
        c = num2 
        if c * c == num1 * num1 + num3 * num3:
            print("Your triangle is a pythagorean triangle")
        else: 
            print("Your triangle isn't a pythagorean triangle")

    elif num3 > num1 and num3 > num2:        
        c = num3 
        if c * c == num2 * num2 + num1 * num1:
            print("Your triangle is a pythagorean triangle")
        else: 
            print("Your triangle isn't a  pythagorean triangle")

    elif num1 == num2 and num2 == num3 and num1 == num3:
        print("There's no such thing as a pythagorean triangle with all sides the same, try again")

        again = str(input("Do you want to continue? [Y/n]\n"))
        if again == "Y" or again == "y":
            pass
        else: 
            break

2 个答案:

答案 0 :(得分:1)

代替编写num1 > num2 and num1 > num3,您可以轻松完成num2 < num1 > num3,它的工作原理相同。

另一方面,我对数字进行排序,不用担心不同的组合:

num1, num2, num3 = sorted( [num1, num2, num3] )

# here the num1 < num2 < num3 so you may use a single check
if num1 * num1 + num2 * num2 == num 3 * num3 : # etc...

答案 1 :(得分:1)

您可以使用max函数和一些数学运算来减少if情况的需要。 下面的示例没有重复循环

num1 = int(input("Type in the first parameter: "))
num2 = int(input("Type in the second parameter: "))
num3 = int(input("Type in the third parameter: "))

if num1 == num2 == num3:
    print("There are no pythagorean triangle with all sides equal")
    exit(1)

c= max(num1,num2,num3)

if c * c == num1 * num1 + num2 * num2 + num3 * num3 - c * c:
    print("Your triangle is a pythagorean triangle")
else: 
    print("Your triangle isn't a pythagorean triangle")