Last modified: Jan 10, 2023 By Alexander Williams
using variable from other functions python
For using variable from another function we need to use Global Variables.
syntax
#global variable
example 1: access a function variable in other function
1 2 3 4 5 6 7 8 9 10 11 12 13 | #function 1 def fun_1(): global user user = "mark" #function 2 def fun_2(): print(user) #run fun_1 fun_1() #run fun_2 fun_2() |
output
mark
example 2: access a function variable in the outside
1 2 3 4 5 6 7 8 | def fun(): global user user = "mark" #run fun fun() #print user variable print(user) |
output
mark
access an outside variable in a function
there are two ways to do that the first is using global variable and the second is declare the variable as a parameter
the first method
1 2 3 4 5 6 7 8 9 10 | global user user = "mark" def fun(): print(user) # run fun fun() |
output
mark
the second method
1 2 3 4 5 6 7 | user = "mark" def fun(user=user): print(user) # run fun fun() |
output
mark