首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >除了在python中重复的if语句之外,还有什么替代方法吗?

除了在python中重复的if语句之外,还有什么替代方法吗?
EN

Stack Overflow用户
提问于 2018-07-23 07:44:19
回答 2查看 236关注 0票数 0

这是我的代码,看起来有点重复,但我想不出一种不同的方法。(顺便说一句,它工作得很好,但在我看来有点“不干净”)

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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-23 08:39:31

您可以使用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")
票数 1
EN

Stack Overflow用户

发布于 2018-07-23 08:04:14

您可以很容易地执行num2 < num1 > num3,而不是编写num1 > num2 and 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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51470100

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档