I started trying to teach myself how to program in python just a few days ago. I have been using a wikibook for non programmers and it has this piece of code as an example. I CAN NOT for the life of me figure out why it outputs the value of the variable a_var from inside the function as being 15 or == to b_var when i change it. I have tried reading over the code multiple times and messing around with the elements of the code to see if i can make it apparent to no avail. I would love it if someone could help clarify this for me.

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)
 
print "a_var = ", a_var
print "b_var = ", b_var
print "c_var = ", c_var
print "d_var = ", d_var

Edit: i do know that this code does not work correctly and it's a little dumb but i got it from an e-book and it is an example. obviously i take no responsibility or credit for it :P

it is equal to 15 because you are passing b_var to the function

c_var = a_func(b_var)
you are getting mixed up between the a_var in the function and the other a_var

i was actually just starting to ask where it was called when i realized that this code

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

didn't actually run until it was called below itself in the program :o
thanks for the help xoxox

Looks like this particular example shows you that function variables are local to the function.

If you want to know what local variables the function has, you can show the local dictionary of the function using vars() ...

def funk1(a):
    c = 7
    print vars()  

a = 1
b = 2
c = 3

funk1(b)  # {'a': 2, 'c': 7}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.