re-calling a function (recursion) vs using the while statement in Python
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Peaceful Mind
--
Chapters
00:00 Re-Calling A Function (Recursion) Vs Using The While Statement In Python
00:36 Accepted Answer Score 3
00:59 Answer 2 Score 0
01:12 Answer 3 Score 0
01:51 Answer 4 Score 1
02:19 Thank you
--
Full question
https://stackoverflow.com/questions/6005...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #recursion #whileloop
#avk47
ACCEPTED ANSWER
Score 3
To be totally honest they both "work" it just depends on your user case. Granted you are more likely to hit recursion depth compared to something going wrong with while they both achieve similar results. Really its more simple and in my opinion slightly more pythonic (in this specific case) to use a while loop. (why make it more complicated?)
ANSWER 2
Score 1
I wouldn't consider it bad practice unless you expect hundreds to thousands of recursive calls, or if memory management is important for your particular application.
As stated in other answers, Python doesn't support tail recursion elimination, which means that a recursive call to the same function doesn't have to add a new stack frame to the stack. This avoids wasting unnecessary memory.
For an interesting read about why Guido, the creator of Python, considers tail recursion elimination to be unpythonic, see: http://neopythonic.blogspot.com/2009/04/tail-recursion-elimination.html
ANSWER 3
Score 0
Shorthand, you say? Compared to:
def ask():
    while input("What is your name? ") != "Tom":
        print ("Who are you?")
    print("Hi, Tom!")
ANSWER 4
Score 0
I suggest to use a while statement, because you will feel difficulties when the ask function become to have its upper limit to try to input and return the result value.
To add these functionality, I modify this function such as:
def ask(count):
    if count < 0:
        return False
    me = input("What is your name? ")
    if me == "Tom":
        print("Hi, Tom!")
        return True
    else:
        print ("Who are you?")
        return ask(count - 1)
Is that implementation so complicated and confusing?
If the ask function is implemented using 'while' statement, the modification is more simple. Just change 'while' to 'for' to set the loop with an upper limit and insert 'return' statement.