Home > Net >  Can I return from two functions at the same time?
Can I return from two functions at the same time?

Time:12-24

So I pretty much want to run a function inside a function, but if a specific condition is true in the second function I want to return from both. I am trying to do the following -

User runs a command to buy something and within that function two other functions are run: one to remove the money from their balance and another to add the item to their inventory. Inside the function to remove the money from their account it checks if they have enough money to buy the item and if not ideally would return from both the function to remove the money and the function that got run first so the function to add the item to their inventory isn't executed.

So sorry if that makes no sense or is confusing. The reasoning for this is so I could use the function to remove money from the user's account multiple times and the functionality to see if they had enough money would only have to be written once within the function that removes the money for ease of use. Is this even possible or is the solution just to write the check every time I need it?

CodePudding user response:

You probably want your first inner function to look something like this

def deduct_money(old_balance, price):

    # find out if they have enough money
    
    if not enough_money:
        return False, old_balance
    # function only continues if user has enough money

    # do other stuff, like deducting the money from their balance

    return True, new_balance

and the outer function would then have something like this

enough_money, new_balance = deduct_money(balance, price)
if not enough_money:
    return False
  • Related