减少尝试的数量和除python

发布于 2025-02-09 23:54:34 字数 1974 浏览 1 评论 0原文

我已经为ATM构建了一个程序,该程序可以检查用户的PIN,然后撤回资金。如果用户的引脚不匹配,则锁定卡。但是,如果确实匹配,它要求用户投入一定数量。如果用户投入的金额不是数字,则提示用户将正确的金额放入,如果用户放入的金额大于其余额大的余额,则会引起错误并退出程序。如果用户投入的金额低于余额,则其撤回资金。我使用了多个例外,但我相信我的代码看起来太令人费解了。有什么更好的方法可以简化我的代码?使用更少的尝试和除外? 还是使用不同的功能进行不同的动作?

user = {
    'pin': 1234,
    'balance': 100
}


def withdraw_cash():
    while True:
        try:
            amount = int(input("Enter the amount of money you want to withdraw: "))
        except ValueError as v:
            print(f"Enter correct amount: ")

        else:
            if amount > user['balance']:
                raise ValueError("You don't have sufficient balance to make this withdrawal")
                is_quit = True

            else:
                user['balance'] = user['balance'] - amount
                print(f"£{amount} successfully withdrawn your remaining balance is £{user['balance']}")
                print('')
                return "Thank you for using Bankomat ATM"

        # finally:
        # print("Program executed")


def bank_atm():
    count = 0
    while count < 3:
        try:
            pin = int(input('Please enter your four digit pin: '))
        except ValueError:
            print("Please enter correct pin")
            count += 1
        else:
            try:
                if pin != user['pin']:
                    print("Pin does not match.. Try Again")
                    count += 1
                else:
                    try:
                        withdraw_cash()
                        return "Thank you for using Bankomat ATM"
                    except ValueError as v:
                        raise v
            except ValueError as v:
                raise v

    if count == 3:
        print('3 UNSUCCESFUL PIN ATTEMPTS, EXITING')
        print('!!!!!YOUR CARD HAS BEEN LOCKED!!!!!')
        is_quit = True
    return "Thank you for using Bankomat ATM"


try:
    bank_atm()
except ValueError as v:
    print(f"ERROR: {v}")

I have built a program for an ATM that checks the pin of a user and also then withdraws money. If the pin of the user does not match, 3 times it locks the card. However, if it does match, it asks the user to put in an amount. If the user puts in an amount that is not a number it asks prompts the user to put in the correct amount, if the user puts in an amount that is larger than the balance it raises an error and exits the program. If the user puts an amount that is less than the balance it withdraws the money. I have used multiple exceptions but I believe my code looks too convoluted. Is there a better way I can simplify my code? Use less try and excepts?
Or use different functions for different actions?

user = {
    'pin': 1234,
    'balance': 100
}


def withdraw_cash():
    while True:
        try:
            amount = int(input("Enter the amount of money you want to withdraw: "))
        except ValueError as v:
            print(f"Enter correct amount: ")

        else:
            if amount > user['balance']:
                raise ValueError("You don't have sufficient balance to make this withdrawal")
                is_quit = True

            else:
                user['balance'] = user['balance'] - amount
                print(f"£{amount} successfully withdrawn your remaining balance is £{user['balance']}")
                print('')
                return "Thank you for using Bankomat ATM"

        # finally:
        # print("Program executed")


def bank_atm():
    count = 0
    while count < 3:
        try:
            pin = int(input('Please enter your four digit pin: '))
        except ValueError:
            print("Please enter correct pin")
            count += 1
        else:
            try:
                if pin != user['pin']:
                    print("Pin does not match.. Try Again")
                    count += 1
                else:
                    try:
                        withdraw_cash()
                        return "Thank you for using Bankomat ATM"
                    except ValueError as v:
                        raise v
            except ValueError as v:
                raise v

    if count == 3:
        print('3 UNSUCCESFUL PIN ATTEMPTS, EXITING')
        print('!!!!!YOUR CARD HAS BEEN LOCKED!!!!!')
        is_quit = True
    return "Thank you for using Bankomat ATM"


try:
    bank_atm()
except ValueError as v:
    print(f"ERROR: {v}")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

许久 2025-02-16 23:54:34

我设法将其简化为奏效!
现在,我将看看是否可以将代码分解为较小的功能,以便可以运行单元测试。

user = {
    'pin': 1234,
    'balance': 100
}


def withdraw_cash():
    while True:
        try:
            amount = int(input("Enter the amount of money you want to withdraw: "))
        except ValueError as v:
            print(f"Enter correct amount: ")
        else:
            if amount > user['balance']:
                raise ValueError("You don't have sufficient balance to make this withdrawal")  
            else:
                user['balance'] = user['balance'] - amount
                print(f"£{amount} successfully withdrawn your remaining balance is £{user['balance']}")
                print('')
                return 
        finally:
            print("Program executed")

def bank_atm():
    count = 0
    to_exit = False
    while (count < 3) and (not to_exit):
        try:
            pin = int(input('Please enter your four digit pin: '))
            print("this worked")
        except ValueError:
            print("Please enter correct pin")
            count += 1
        if pin != user['pin']:
            print("Pin does not match.. Try Again")
            count += 1
        else:
            withdraw_cash()
            to_exit = True
    if count == 3:
        print('3 UNSUCCESFUL PIN ATTEMPTS, EXITING')
        print('!!!!!YOUR CARD HAS BEEN LOCKED!!!!!')
    


try:
    bank_atm()
except ValueError as v:
    print(f"ERROR: {v}")

I have managed to reduce it to this, which worked!
I am now going to see if I can break my code into smaller functions so I can run unit tests.

user = {
    'pin': 1234,
    'balance': 100
}


def withdraw_cash():
    while True:
        try:
            amount = int(input("Enter the amount of money you want to withdraw: "))
        except ValueError as v:
            print(f"Enter correct amount: ")
        else:
            if amount > user['balance']:
                raise ValueError("You don't have sufficient balance to make this withdrawal")  
            else:
                user['balance'] = user['balance'] - amount
                print(f"£{amount} successfully withdrawn your remaining balance is £{user['balance']}")
                print('')
                return 
        finally:
            print("Program executed")

def bank_atm():
    count = 0
    to_exit = False
    while (count < 3) and (not to_exit):
        try:
            pin = int(input('Please enter your four digit pin: '))
            print("this worked")
        except ValueError:
            print("Please enter correct pin")
            count += 1
        if pin != user['pin']:
            print("Pin does not match.. Try Again")
            count += 1
        else:
            withdraw_cash()
            to_exit = True
    if count == 3:
        print('3 UNSUCCESFUL PIN ATTEMPTS, EXITING')
        print('!!!!!YOUR CARD HAS BEEN LOCKED!!!!!')
    


try:
    bank_atm()
except ValueError as v:
    print(f"ERROR: {v}")

情释 2025-02-16 23:54:34

您可以通过IF-Else语句和一个计数器来实现这一切。

user = {
    'pin': 1234,
    'balance': 100
}

def withdraw_cash():
    while True:
        amount = input("Enter the amount of money you want to withdraw: ")
        if not int(amount):
            print(f"Enter correct amount: ")
        else:
            amount = int(amount)
            if amount > user['balance']:
                raise ValueError("You don't have sufficient balance to make this withdrawal")
                is_quit = True

            else:
                user['balance'] = user['balance'] - amount
                print(f"£{amount} successfully withdrawn your remaining balance is £{user['balance']}")
                print('')
                return "Thank you for using Bankomat ATM"


def main():
    count = 0
    while count < 3:
        pin = input('Please enter your four digit pin: ')
        if not int(pin):
            print("Please enter correct pin")
            count += 1
        else:
            pin = int(pin)
            if pin != user['pin']:
                print("Pin does not match.. Try Again")
                count += 1
            else:
                print(withdraw_cash())
                raise SystemExit

    if count == 3:
        print('3 UNSUCCESFUL PIN ATTEMPTS, EXITING')
        print('!!!!!YOUR CARD HAS BEEN LOCKED!!!!!')
        is_quit = True
    return "Thank you for using Bankomat ATM"


main()

You could achieve all this with just if-else statements and a single counter.

user = {
    'pin': 1234,
    'balance': 100
}

def withdraw_cash():
    while True:
        amount = input("Enter the amount of money you want to withdraw: ")
        if not int(amount):
            print(f"Enter correct amount: ")
        else:
            amount = int(amount)
            if amount > user['balance']:
                raise ValueError("You don't have sufficient balance to make this withdrawal")
                is_quit = True

            else:
                user['balance'] = user['balance'] - amount
                print(f"£{amount} successfully withdrawn your remaining balance is £{user['balance']}")
                print('')
                return "Thank you for using Bankomat ATM"


def main():
    count = 0
    while count < 3:
        pin = input('Please enter your four digit pin: ')
        if not int(pin):
            print("Please enter correct pin")
            count += 1
        else:
            pin = int(pin)
            if pin != user['pin']:
                print("Pin does not match.. Try Again")
                count += 1
            else:
                print(withdraw_cash())
                raise SystemExit

    if count == 3:
        print('3 UNSUCCESFUL PIN ATTEMPTS, EXITING')
        print('!!!!!YOUR CARD HAS BEEN LOCKED!!!!!')
        is_quit = True
    return "Thank you for using Bankomat ATM"


main()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文