za*****@gmail.com wrote:
Im working with python2.2 on red hat linux.
The following program is supposed to print decreasing numbers from an
entered number till 1, each decrement being = 1 :
#! usr/bin/env/python
def f(n=int(raw_input("enter number: "))):
print 'n=',n
if n>1:
return n*f(n-1)
else:
print 'end'
return 1
Though it works fine on the python interpretor, i dont get the
required output when i write this code in gedit (text editor). The
output that i get is (where t4.py is the name of the file):
[root@localhost root]# python t4.py
enter number: 6
[root@localhost root]#
i.e it takes the input but doesn't print anything. If anybody can
help... Thanx!
Hello,
When you run it through the interpreter, then the interpreter "looks"
at your definition of f, "understands" it, and continues on. What
follows your definition of f? Nothing. In particular, nothing instructs
the interpreter to *execute* f. So your problem is not that f is being
executed but is not printing anything, but rather that f is not being
executed.
To do what you want it to do, maybe try the following:
#! usr/bin/env/python
def f(n):
print 'n=',n
if n>1:
return n*f(n-1)
else:
print 'end'
return 1
if __name__ == '__main__':
n = int(raw_input("enter number: "))
f(n)
The line (if __name__...) means that if the interpreter is running your
module the way you mean here, then it should get the raw input for n,
then call f.
HTH,
Efrat
P.S. Note that I changed your f so that it doesn't do input itself.
Coupling calculation code with user-interaction code is maybe not so
good (IMHO).