0

Why Python can access variable in function which was defined outside of function. This mysterious_var was defined outside but how Python can access it in function?

 def show_truth():
        print(mysterious_var)
        
 mysterious_var = 'Surprise!'
        
 show_truth()

1 Answer 1

2

You need to understand the concept of flow of control in python.. So lets take your code as an example.

So the flow of control would be something like this.

1 -> Line number one(defining your function and storing its reference in the RAM) Remember, the flow of control will not move into the function as of now because the function in line 1 has just been defined, it hasn't been called yet.

2 -> Line number 3(assigning the variable)

3 -> Line number 4(Calling the function)

4 -> Line number 1 again(It will move onto the line number 1 as you called the function)

5 -> The code inside the function.

Now if you realize the variable has already been defined and assigned in the step 3. So the code inside your function recognizes the variable and does not produce any errors.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for this it was eyeopener especially for point 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.