a = 10
def foo(x = a):
   print x

a = 5
foo()

Can someone explain why it prints 10 ?

Recommended Answers

All 2 Replies

There are 3 things going on with your script.
1. a is global variable assigned the value of 10.
2. You function is a function that has a default value set. that is global a which got the value of 10.
due to that

foo()

will print the default value which is

def foo(x=10)

because a=10. So when you call

foo()

it will return the default value.

Try and call foo(a) on line 6. This will print the current value of a which is 5.

3.Variable scope and function definations are very simple once you master them.
As you can see.

foo()

took no value. As long as you dont give a value to

foo()

.... It will keep printing the value of first a which is 10.

Try and change the value of first a and call

foo()

without a value to see.

Hope you get the idea. happy codding :)

Thanks for explaining :)

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.