如何使用系统出口()?

2024-10-03 11:21:30 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在这个while循环中使用sys.exit()?在

用户输入三角形的3条边。如果它是一个直角毕达哥拉斯三角形,那么它就会打印出来。在

如果用户输入“0”,程序结束。在

另外,除了使用count=0且从不递增外,还有没有更好的方法来编写无限while循环?在

def pythagoreanTriple():
    count = 0
    print("input 3 sides of a triangle")
    print("or enter 0 to quit")
    while count < 1:
        sides = []
        for i in range(0, 3):
            side = int(input("Input a side: "))
            sides.append(side)
        sides = sorted(sides)
        if sides[0] ** 2 + sides[1] ** 2 == sides[2] ** 2:
            print('That is a Pythagorean Triple!')
        else:
            print('That is not a Pythagorean Triple...')
    else:
        sys.exit(0)

pythagoreanTriple()

Tags: 用户inputthatiscountsysexitside
2条回答

您可以将代码段包装在一个无限循环中,break只有在条件。满足条件:

def pythagoreanTriple():
    while True:
        userInp = input("Enter 1 to continue 0 to exit: ")
        if userInp.lower() == "0":
            break
        sides = []
        for i in range(0, 3):
            side = int(input("Input a side: "))
            sides.append(side)
        sides = sorted(sides)
        if sides[0] ** 2 + sides[1] ** 2 == sides[2] ** 2:
            print('That is a Pythagorean Triple!')
        else:
            print('That is not a Pythagorean Triple...')

pythagoreanTriple()

输出

^{pr2}$

您需要将sys.exit()放入while循环中,否则它永远不会停止。在

此外,为了有一个无限循环,大多数人使用while True。在

相关问题 更多 >