输入数字以外的字符时如何使我的程序不崩溃

时间:2018-11-13 05:40:41

标签: python-3.x

我正在尝试制作一个银行程序。我已经完成了大部分代码,但是我只能坚持一件事。每次我尝试存入或提取一个与数字不同的字符时,我的程序都会崩溃。我只是想知道如何使用try和except语句来使它不会崩溃。我的代码附在下面。

def printmenu():
    print("======================")
    print("Welcome to Dons Bank")
    print("What can I do for you?")
    print("1 - Withdraw Funds")
    print("2 - Deposit Funds")
    print("3 - Show Balance")
    print("4 - Quit")

    def main():
        myBalance = 1000
        userChoice = 0
        invalidcharac = True
        printmenu()
        while invalidcharac:
            try: 
                userChoice = int(input("Please choose one of the above options: "))
                invalidcharac = False
            except ValueError:
                print("Invalid option.  Please choose an option by entering 1, 2, 3, or 4.")
        while userChoice != 4:
            if userChoice == 1:
                amount = int(input("Amount to withdraw: "))
                while myBalance - amount < 0:
                    print("Sorry: you don't have that much money in your account.")
                    amount = int(input("Amount to withdraw: "))
                myBalance = myBalance - amount
                print("New balance: ", myBalance)
            elif userChoice == 2:
                amount = int(input("Amount to deposit: "))
                myBalance = myBalance + amount
                print("New balance: ", myBalance)
            elif userChoice == 3:
                print("Balance: ", myBalance)
            elif userChoice == 4:
                continue
            else:
                print("Invalid option. Please choose an option by entering 1, 2, 3, or 4.")
        print("Thank you. Goodbye!")

    main()

1 个答案:

答案 0 :(得分:0)

与往常一样,您可以调整消息

<intent-filter android:label="@string/app_name" android:autoVerify="true">
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="https" android:host="app.page.link" />
    <data android:scheme="http" android:host="appshareoffer.page.link" />
</intent-filter>