如何结束程序(Python)?

时间:2017-10-14 11:46:13

标签: python loops if-statement while-loop terminate

我是Python3编码的新手,我在这里遇到了问题。 在第14行,我打算通过打印结束这个程序"谢谢!再见"在你回答的部分" n"到"再试一次?"。然而,事实证明,即使我已插入" break"我也会重新开始。在它下面。现在,我能提出的唯一解决方案是用sys.exit(0)结束整个程序,但我不认为它是一个理想的解决方案,因为它只会关闭整个程序。

import sys
while True:

x=int(input("Enter the coins you expected="))
f=int(input("Enter first coin="))

while f!=1 and f!=5 and f!=10 and f!=25:
   print("invalid number")
   f=int(input("Enter first coin="))

if x>f:
    while x>f:
        n=input("Enter next coin=")
        if not n:
            print("Sorry-you only entered",f,"cents")
            again=input("Try again (y/n)?=")
            if again=="y":
                True
            elif again=="n":
                print("Thank you, goodbye!")
                sys.exit(0)
            break

        while int(n)!=1 and int(n)!=5 and int(n)!=10 and int(n)!=25:
            print("invalid number")
            n=input("Enter next coin=")
        f=f+int(n)

1 个答案:

答案 0 :(得分:1)

用以下代码替换整个代码:

import sys

Stay = True

while Stay:

    x = int(input("Enter the coins you expected = "))
    f = int(input("Enter first coin = "))

    while f != 1 and f != 5 and f != 10 and f != 25:
        f = int(input("Invalid number entered./nEnter first coin = "))

    while x > f and Stay:

        n = input("Enter next coin = ")

        if not n:

            print("Sorry, you only entered " + str(f) + " cents")
            again = input("Try again (y/n)?=")

            if again == "n":
                print("Thank you, goodbye!")
                Stay = False

        if Stay:

            n = int(n)
            while n != 1 and n != 5 and n != 10 and n != 25:
                print("Invalid number entered.")
                n = int(input("Enter next coin = "))
            f += n

我使代码更具可读性,并使用布尔标志(Stay)修复了问题。这基本上意味着该程序在StayTrue时运行,而Stay在用户输入False后变为'n'