How to Create Locally Scoped Variables Within a Function in Python


In this example we will show how to create locally scoped variables within a function in Python.

Source Code

def my_func():
    var1 = 6
    print(var1)

my_func()

# a variable created inside a function  can only be used inside that function
print(var1)

Output:

6
Traceback (most recent call last):
  File "demo.py", line 8, in 
    print(var1)
NameError: name 'var1' is not defined
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments