Answer to Question #235717 in Python for Anaya Farhan

Question #235717

Show what happens when a variable defined outside a function has the same name as a local variable inside a function. Explain what happens to the value of each variable as the program runs.


1
Expert's answer
2021-09-10T18:52:24-0400

In fact - nothing will happen. Each variable will live it's own life in it's scope.

Example:

def my_func():
    var = 20  # inner variable
    return var

var = 10  # outer variable
print(var)
print(my_func())
print(var)

Output:
10
20
10

Any change of inner variable var will not affect outer variable var and vice versa.

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS