0

My question is that I was writing a program in Python 3 trying to think of a way to repeat a function from within a function, when on StackOverflow I found I can do this with the else statement:

def program(): 
var = (input('Pick A Car: BMW Or Nissian')) 
if var == 'BMW':
    print('You Picked BMW \n') 
if var == 'Nissian':
    print('You Picked Nissian \n') 
    else:
        print('That's Not An Option') 
        program() 
        return 

But I just do not understand how calling back a function from within a function can happen considering that the full function has not been defined yet? I appreciate the help if possible!

  • Some useful reading material: [What Is Recursion?](http://interactivepython.org/courselib/static/pythonds/Recursion/recursionsimple.html) or [Non-Programmer's Tutorial for Recursion in Python](http://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3/Recursion) – logic Apr 03 '15 at 02:14

1 Answers1

0

The function is defined. You define it right there. Assuming the indentation in your actual code is correct, your code should mostly work (you should use elif var == 'Nissian': instead of if var == 'Nissian').

Repeating a function within a function is called "recursion." There is a wealth of information about it online.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • One thing I do not understand is the point of the return keyword after calling the function @TigerhawkT3 – jediquest1 Apr 03 '15 at 06:01
  • You don't need to `return` at the end of a function. Python does that automatically. The key to a recursive algorithm is an ending condition that tells the function to stop recurring. [Calculating Fibonacci numbers](http://stackoverflow.com/questions/22111252/tail-recursion-fibonacci) is a [classic recursion exercise](http://stackoverflow.com/questions/8965006/java-recursive-fibonacci-sequence). – TigerhawkT3 Apr 03 '15 at 06:19
  • Okay, I think I understand now, so if the IF condition is met it will run normally, if the ELSE condition is met it will run the PRINT statement and then repeat the program() function to then test the IF statements again because the top block of code in program() is already defined so it can run program() from within program(), is that right? (And sorry for the indentation error in the original question) @TigerhawkT3 – jediquest1 Apr 03 '15 at 06:39
  • The whole thing is already defined. That recursive call isn't the first time it was called - it had to first be called from outside. After that, yes, it will keep calling itself again and again until the ending condition is satisfied, and then it ends. – TigerhawkT3 Apr 03 '15 at 06:54