簡體   English   中英

如何結束程序(Python)?

[英]How to end the program (Python)?

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

用這個替換你的整個代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM