[英]How do I use sys.exit()?
如何在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()
你需要把你的sys.exit()
放在你的while
循環中,否則它永遠不會停止。
而且,為了擁有無限循環,大多數人使用while True
。
您可以將片段包裝在無限循環中,並僅在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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.