[Tutor] From newbie. Defining Functions
SA
sarmstrong13@mac.com
Wed, 14 Aug 2002 08:27:46 -0500
On 8/14/02 7:34 AM, "akira sugiura" <kodokuchef@yahoo.com> wrote:
> Hi,
>
> I tried to figure out why the "print "in a_func
> a_var=",a_var"line outputs "15", Instead of "10" but I
> still can't figure it out. Could anyone explain this
> to me? Thank you very much.
> ======================================================
>
>
> a_var = 10
> b_var = 15
> e_var = 25
>
> def a_func(a_var):
> print "in a_func a_var = ",a_var
> b_var = 100 + a_var
> d_var = 2*a_var
> print "in a_func b_var = ",b_var
> print "in a_func d_var = ",d_var
> print "in a_func e_var = ",e_var
> return b_var + 10
>
> c_var = a_func(b_var)
>
Python reads everything from top to bottom. So when you say:
c_var = a_func(b_var)
You have now just switched b_var with a_var in your function. That is kind
of a generic explanation. And c_var is now been assigned the output from
bvar + 10 inside a_func. You have done nothing to clear the a_var in your
function.
What I think you may have intended to do for this function is:
def a_func():
print "in a_func a_var = ",a_var
b_var = 100 + a_var
d_var = 2*a_var
print "in a_func b_var = ",b_var
print "in a_func d_var = ",d_var
print "in a_func e_var = ",e_var
return b_var + 10
This will now pass the correct values from all of your first assigned
variables. And when you say c_var = a_func(b_var), b_var will be passed to
b_var instead of a_var within your function. Basically, the a_var in the
line "def a_func(a_var):" is nothing more than a place holder to pass in a
variable. And since it has the same name as the a_var in the function, all
a_var inside the function namespace will have the same value as the variable
you passed to the function. Does that make since?
Think of it as similar to the math term f(x). I think that is a close enough
analogy.
Hope this helps.
SA
P.S. Man this stuuf is starting to get scary now that it is beginning to
make sense to me.
--
"I can do everything on my Mac I used to on my PC. Plus a lot more ..."
-Me