Search code examples
pythonfunctionloopsrepeatredo

Creating "redo" function to return to beginning of multiple functions in Python


How do i make the 'redo' function return to the beginning of multiple different functions? I want it to return the beginning of the starting function but due function name changing, the redo function would not apply to the any other functions than the first one. Any help is appreciated, thanks in advance!

Example of what i'm trying to do:

function_1():
  print('x')
  redo()

function_2():
  print('y')
  redo()

def redo():
 while True:
    redo = input("Would you like to redo this section?\nEnter y/n: ")
    while redo not in ('y', 'n'):
            print("Please enter a valid input.\n")
    if redo == 'y':
        (original function its under) 
    elif redo == 'n':
        break

Solution

  • A function can't directly change the control flow of its caller, but it can return a condition that the caller can use to modify its own control flow:

    def function_1():
        run = True
        while run:
            print('x')
            run = redo()
    
    def function_2():
        run = True
        while run:
            print('y')
            run = redo()
    
    def redo():
        while True:
            redo = input("Would you like to redo this section?\nEnter y/n: ")
            if redo == 'y':
                return True
            if redo == 'n':
                return False
            print("Please enter a valid input.")