[Tutor] finding factorials
lonetwin
lonetwin@yahoo.com
Mon Jun 30 05:49:01 2003
Hi Payal,
On Monday 30 Jun 2003 1:01 pm, Payal Rathod wrote:
> My very basic solution is going totally wrong,
>
> #!/usr/local/bin/python
> def euclid(a,b):
> c = a
> a = b
> b = c % a
> if b != 0:
> euclid(a,b)
> return a
This function looks ok. However, the three statements
> c = a
> a = b
> b = c % a
could be shortened to
a, b = b, a%b
If you can't understand right away what the above statement does, don't
worry about it. Maybe you could have a look at the python tutorial (Sec 3.2)
sometime later to learn this neat trick.
> b = 5
What does this line do ?? Yup, It defines 'b = 5', but since it is not
part of the function 'euclid', this "b" is not the same as the "b" in the
function. The "b" within the function is called a local variable. It is
created when the function is invoked (like in your next statement) and
disappears as soon as the function returns. Whereas, the "b" outside the
function is know as a 'global' because it is visible throughout the file
after it's definition and does not get deleted (unless explicitly passed to
the del() builtin) till the program ends.
> euclid(10,5)
Here you could possibly have done
a = 10
b = 5
euclid(a, b)
However, you should remember, the a and b here are globals and tho' they
are visible throughout the file all through the execution of the program
(like I mentioned above), the "local" a and b from the euclid definition will
override these. However, coincidently, the local a and b will receive the
values 10 and 5, because you passed those values in that order.
instead if you had said
euclid (b, a)
within euclid (ie the local values of ..)
a would be 5
and b would be 10
> print a
Since in your program you did not define an 'a' outside the function this
statement will give you a "NameError" and I believe this is what you mean
when you said:
> It is giving errors.
On this list you are encouraged to post your tracebacks/error messages,
bcos these messages tell you (surprise, surprise !!) what the errors are. Run
your program once again and try to read the error message reading one line at
a time from bottom up.
> Can someone guide me to a proper solution?
Well, now you know the reason why your solution was failing, why don't you
give it another shot ??
HTH
Peace
Steve
--
panic ("Splunge!");
2.2.16 /usr/src/linux/drivers/scsi/psi240i.c