def test1():
print(x)
def test2(x):
print(x)
x=1
test1()
test2(x)
When I run this python code, I get:
1
1
How can function test1 know about x, without passing it as an argument?
def test1():
print(x)
def test2(x):
print(x)
x=1
test1()
test2(x)
When I run this python code, I get:
1
1
How can function test1 know about x, without passing it as an argument?
A variable which is defined in the main body of a file is called a global variable.
It will be visible throughout the file, and also inside any file which imports that file.
Here x
is a global varaible.
try the below code
def test1():
x=2
print(x)
def test2(x):
print(x)
x=1
test1()
test2(x)
Here the output will be
2
1
Because test1 will print its local variable x
.
You can use global
keyword to modify the value of global variable x
in test1()
def test1():
global x
x=2
print(x)
def test2(x):
print(x)
x=1
test1()
test2(x)
Output
2
2