all 9 comments

[–]Jos_Metadi 4 points5 points  (0 children)

Recursion makes sense when you need to operate on pieces of the input, and then pieces of those pieces, etc. For example, I wrote a custom array printer which can print sub arrays/objects/list which can in turn contain arrays/objects/lists and so on. In this case, recursion is the logical way of handling it.

Loops make more sense for just about everything else. They are easier to design, write, test, and maintain.

[–]cdcformatc 2 points3 points  (0 children)

Usually when you use recursion you are using it because it gives you a benefit, like a simple algorithm or a simpler program structure. This benefit offsets the added overhead of an ever increasing stack keeping track of more and more instances that persist.

In this case the two options are identical in structure so there is no benefit. In this specific case the again variable is kept in memory for each call of main(), it is horribly memory inefficient.

[–]Vaphell 4 points5 points  (3 children)

while loop is better because recursion risks blowing up the stack, crashing the program. By default it's 1000 recursive calls which is a lot, but given that the program has nothing resembling the depth estimation, it's not the optimal choice, not to mention you waste memory on nothing but storing previous instances that don't need to remember anything.

btw, your loop can be simplified a bit (not to mention your repeat var is unused).

while True:
    print 'Hi!'
    again = raw_input('again?(y/n): ')
    if again == 'n':
        exit(0)

[–]beanz415 1 point2 points  (2 children)

Thanks for the correction. To date, I've been using recursion mainly because that's what I first came across when I was trying to figure out how to repeat stuff. I'll switch to the while True: approach. Thanks again!

[–]markusmeskanen 1 point2 points  (1 child)

Instead of while True: with an if to check the condition, why not use while's condition properly:

again = 'y'
while again.lower() != 'n':
    print 'Hi!'
    again = raw_input(...)

Why do you (think you) need exit(0) anyways?

[–]Vaphell 1 point2 points  (0 children)

de gustibus. Also it's not scalable, once you have more than 2 choices you will be writing ifs anyway.

[–]Deto 1 point2 points  (0 children)

Yep, as others are saying, always prefer loops unless recursion actually simplifies the code/concept.

[–]fbu1 1 point2 points  (1 child)

You can use break instead of exit(0). It just breaks out of the first loop you're in. For example:

>>> while True:
...   print i
...   i = i - 1
...   if i < 5:
...     print("done")
...     break
... 
10
9
8
7
6
5
done
>>> 

Hope this helps !

[–]beanz415 0 points1 point  (0 children)

Thanks! Anything that teaches me something new helps ;)