Originally Posted by
unutbu
If you use "n==0" and someone were to be so unwise as to run
then they fall into an infinite loop.
And not only someone will consciously do that, it might happen at random, say:
PHP Code:
x = 10
y = 5
# ... code here ...
y += 6
print_n('Hello', x - y)
Thus, the problem becomes transparent to the person (including yourself) using the function. The thing is, functions are enclosed objects that should behave as expected, therefore, I don't expect that when calling a function made by other person (say you created a library and I'm using it) it will go on a infinite loop and crash my program.
The "pythonic" (well, object-oriented) way to handle it is by throwing the proper error:
PHP Code:
def recursion(s, n):
if n == 0:
return None
elif n < 0:
raise ValueError("Argument 'n' must be positive.")
print s
recursion(s, n-1)
But exception Handling is not something I would mess with at this point, so leave that for later.
Bookmarks