[Solved] Revisiting Functions In Python 3


Whenever you have Python code that is:

Recalling The Same Function So That If The User Does Not Chose One Of The Other Statements Then They Can Try Again Rather Than The Program To Stop Working,

you are almost always better off replacing the recursive call with a loop. In this case the recursion is completely unnecessary, probably wastes resources and arguably makes the code harder to follow.

edit: Now that you’ve posted the code, I’d suggest recasting it as a state machine. The following page provides a summary of Python modules that could be useful: link.

Even without any additional modules, your code lends itself to a simple non-recursive rewrite:

import sys

def function_four():
    # Does Stuff
    return function_one

def function_three():
    # Does Stuff
    return function_two

def function_one():
    usr_input = input("Options: '1') function_three | '2') Quit\nOption: ")
    if usr_input == '1':
        return function_three
    elif usr_input == '2':
        return None
    else:
        print("Did not recognise command. Try again.")
        return function_one

def function_two():
    usr_input = input("Options: '1') function_four | '2') function_three | '3') Quit\nOption: ")
    if usr_input == '1':
        return function_four
    elif usr_input == '2':
        return function_three
    elif usr_input == '3':
        return None
    else:
        print("Did not recognise command. Try again.")
        return function_two

state = function_one
while state is not None:
    state = state()

Note that the functions no longer call each other. Instead, each of them returns the next function to call, and the top-level loop takes care of the calling.

6

solved Revisiting Functions In Python 3