# how to think like a computer scientist

Colin J. Williams cjw at sympatico.ca
Sun Nov 13 15:16:51 CET 2005

```Brian van den Broek wrote:
> john boy said unto the world upon 2005-11-11 22:25:
>
>> Question for the following program: sec 5.5
>>
>> def factorial (n):
>>    if n == 0:
>>       return 1
>>    else:
>>       recurse = factorial (n-1)
>>       result = n * recurse
>>       return result
>>
>> How come whenever I state the function with "n" given a value it
>
>
> <snip>
>
>
>>
>> So instead I have to give a "print" command to make the result appear
>> in the interpreter for EX:
>
>
> <snip>
>
>> Is this correct....should I have to give a print command??
>
>
>
> Hey,
>
> I assume you mean when you run it as a script; when I run it as the
> interactive prompt, I get output:
>
> IDLE 1.1.2
>  >>> def factorial (n):
>     if n == 0:
>           return 1
>         else:
>         recurse = factorial (n-1)
>         result = n * recurse
>         return result
>
>  >>> factorial(3)
> 6
>
> In general, it would be bad if the interpreter decided to print
> everything you asked it to compute. The function returns the result of
> the factorial(n) call, and it is up to your code to decide what to do
> with it. If the only use is to print it, then
>
> print factorial(3)
>
> might be what you want. But it is also possible you'd want to store the
> result for further computation, and would find the print an unwanted
> 'feature'. So,
>
> important_for_later = factorial(some_num)
>
> Best,
>
> Brian vdB
>
Looks OK to me, prints 120.
Could be a little simpler:
def factorial (n):
if n == 0:
return 1
else:
return n * factorial (n-1)
print factorial(5)

Colin W.

```