Can I return from two functions at the same time?

Question:

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?

Asked By: Slimey

||

Answers:

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
Answered By: yagod
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.