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

How to prevent Function B returning 'none' to Function A that calls it, after function B calls function C and returns to itself

Apologies for the confusing title, but here is a very simplified version of what I mean:

def main():
    burger = 0
    shake = 0

    run = True
    while run:
        choice = show_menu()

        if choice == "burger":
            qt_burger += 1
        elif choice == "shake":
            qt_shake += 1
        else:
            show_bill

def show_menu():
    choice = input("Burger or Shake?: ")
    if choice not in ["burger", "shake"]:
        show_error(choice)
    else:
        return choice

def show_error(choice):
    print(f"{choice} is not an option")
    show_menu()

main()

Function ‘main’ defines variable ‘choice’ based on what is returned from function ‘show_menu’. If show_menu does not call show_error, the program properly returns the input value back to ‘choice’ in ‘main’. However, if show_error is called, show_menu is called again, and a proper value is entered the second time, choice in main becomes ‘none’. Is there any way around this while keeping all these separate functions? I have also tried re-calling show_menu from within itself rather than from within the error function, but it is the same result.

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 :

Incase of choice is invalid, you are calling show_error, after executing this function(show_error) the interpreter will just move to next line i.e the end of show_menu function which implicitly return None
.But if you return show_error(), the interpreter will execute this function and return whatever value show_error will return.


def show_menu():
    choice = input("Burger or Shake?: ")
    if choice not in ["burger", "shake"]:
        return show_error(choice)
    else:
        return choice

def show_error(choice):
    print(f"{choice} is not an option")
    return show_menu()

A simpler(more readable) way can be

def read_input():
    return input("Burger or Shake?: ")

def show_menu():
    choice = read_input()
    while choice not in ["burger", "shake"]:
        show_error(choice)
        choice = read_input()
    return choice

def show_error(choice):
    print(f"{choice} is not an option")

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