【问题标题】:How to end the program (Python)?如何结束程序(Python)?
【发布时间】:2018-03-26 10:21:20
【问题描述】:

我是 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)

【问题讨论】:

  • 您的问题得到解答了吗?
  • 是的,我的问题得到了解答,它奏效了:)!

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


【解决方案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时运行,当用户输入'n'Stay变为False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-24
    • 2016-10-31
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多