如何使用sys.exit()?

时间:2019-04-01 13:54:13

标签: 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()

2 个答案:

答案 0 :(得分:0)

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

此外,为了产生无限循环,大多数人都使用while True

答案 1 :(得分:0)

您可以将代码段无限循环地包装,只有在cond时才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()

输出

Enter 1 to continue 0 to exit: 1
Input a side: 5
Input a side: 5
Input a side: 10
That is not a Pythagorean Triple...
Enter 1 to continue 0 to exit: 0

Process finished with exit code 0