how to think like a computer scientist
Brian van den Broek
broek at cc.umanitoba.ca
Sun Nov 13 05:24:48 EST 2005
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 prints no results in the interpreter for EX:
<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
More information about the Python-list
mailing list