Last modified: Aug 19, 2023 By Alexander Williams

2 ways to Use The Same Variable In Different Functions Python

 In this article, we'll learn 2 ways to use the same variable in different functions in Python. The first way is Global Variable, and the second is Function Parameter

Global keyword

The global keyword tells Python that the variable is defined in the global scope and can be accessed by all functions. For example:

# Global variable
global_variable = 10

# Define the first function
def function1():
    # Print the value of the global variable
    print(global_variable)

# Define the second function
def function2():
    # Print the value of the global variable
    print(global_variable)

# Call the 'function1'
function1()

# Call the 'function2'
function2()

Output:

10
10

Here is the explanation of the code in steps:

  1. Define a global variable called global_variable and assigns it the value 10. 
  2. Define a function called function1() that prints the value of the global variable.
  3. Define a function called function2() that prints the value of the global variable.
  4. call function1() and function2()

Function Parameter

You can also pass the variable as a parameter to a function to use the same variable in different functions. Here is an example:

# Define two functions

def function1(variable):
    print(variable)

def function2(variable):
    print(variable)

# Set a shared variable to the value 10.
shared_variable = 10

# Call both functions, passing the shared_variable as an parametre.
function1(shared_variable)
function2(shared_variable)

 Output:

10
10

In this case, the value of the variable variable is passed by reference to the functions function1() and function2(). Any changes to the variable value will be reflected in both functions.

Difference between Global Variable and Function Parameter

Here are the differences between global variables and function parameters:

Feature Global variable Function parameter
Scope Visible to all functions in the program Visible only to the function that it is defined in
Initialization Can be initialized anywhere in the program Must be initialized in the function definition
Passing by value Not passed by value Always passed by value
Changing the value Can be changed by any function in the program Can only be changed by the function that it is defined in


Conclusion

Ultimately, we've learned how to use the same variable in multiple functions using global keywords and function arguments. Both are working well, but in some ways, they are different.