# Define a global variable my_var = 10 # Define a function that uses the global variable def my_function(): # Declare the variable as global global my_var # Use the global variable my_var += 1 # Call the function my_function() # Print the global variable print(my_var)
To use a global variable in a function in Python, you must first declare the variable as global in the function using the global keyword.
It's important to note that using global variables can make your code difficult to read and maintain, and can also cause unexpected behaivor if the same global variable is modified by multiple functions. It's generally better to avoid using global variables whenever possible, and instead pass the necessary variables as arguments to the function.
Here's an example of how you can avoid using global variables by passing the necessary variables as arguments to the function:
# Define a variable my_var = 10 # Define a function that uses the variable def my_function(var): # Use the variable var += 1 return var # Call the function and pass the variable as an argument my_var = my_function(my_var) # Print the variable print(my_var)This will also print 11, but without using global variables.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.