Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I return from two functions at the same time?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading