Ethan Bierlein
Ethan Bierlein

Reputation: 3535

Why is using a while loop better?

I am making a program that uses a loop to run forever and I have a snippet of code below to show you how I acheive the loop. This is just an example and not the actual program. It is the same idea though.

import time
def start():
    print "hello"
    time.sleep(0.2)
    start()
start()

All of my programmer friends tell me not to do this, and use a while loop instead. Like this:

import time
def start():
    while True:
        print "Hello"
        time.sleep(0.2)
start()

Why should I use the while loop instead when both methods work perfectly fine?

Upvotes: 1

Views: 124

Answers (4)

Srikar Appalaraju
Srikar Appalaraju

Reputation: 73588

Each time you are recursing, you are pushing a frame context onto your program stack. Soon you would have used up your entire allotted stack space causing stackoverflow, no pun intended ;)

The second approach has no such flaws. Hence by the looks of it 2nd is better than 1st approach (unless more of the program is presented).

Upvotes: 6

user2864740
user2864740

Reputation: 61865

Python does not have Tail Call Optimization (TCO) and cannot elide the stack. As such, recursion should not be used for an unbound depth (in languages without TCO) lest you get a stack-overflow error!

While the current code might appear to be fine, consider this simple change which will quickly reveal a problem.

def start():
    print "hello"
    # let's go faster! -- time.sleep(0.2)
    start()
start()

Upvotes: 1

Pruthvi Raj
Pruthvi Raj

Reputation: 3036

the while loop amd recursion both have their advantages and disadvantages but while loop is just a test and conditional jump. wheras ecursion involves pushing a stack frame, jumping, returning, and popping back from the stack.So they might have preferred while loop :)

Upvotes: 1

falsetru
falsetru

Reputation: 368964

If you run the program continuously with the recursion, you will get RuntimeError:

Traceback (most recent call last):
  File "t.py", line 8, in <module>
    start()
  File "t.py", line 7, in start
    start()
  File "t.py", line 7, in start
    start()
  ...
  File "t.py", line 7, in start
    start()
RuntimeError: maximum recursion depth exceeded

>>> import sys
>>> sys.getrecursionlimit()
1000

Upvotes: 2

Related Questions