Home > Mobile >  Reduce the number of try and except in python
Reduce the number of try and except in python

Time:06-23

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}")

CodePudding user response:

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


def withdraw_cash():
    while True:
        amount = input("Enter the amount of money you want to withdraw: ")
        if type(amount) != int:
            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"


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

    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()

CodePudding user response:

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}")

  • Related