def update_value(n): n = n + 1 num = 5 update_value(num) print(num) # Output: 5
In Python, variables are passed by reference. This means that when you pass a variable to a function, the function is able to modify the variable in its original location in memory.
In the above example, the update_value function takes an argument 'n' and modifies it by adding 1 to its value. However, when we print the value of 'num' after calling the update_value function, we see that it remains unchanged. This is because the update_value function only modifies the local copy of the 'n' variable, which is created when the function is called.
To modify a variable in the caller's scope, you need to use the 'global' keyword to explicitly declare the variable as being in the global scope. Here's how you can modify the 'num' variable by using the 'global keyword':def update_value(n): global n n = n + 1 num = 5 update_value(num) print(num) # Output: 6In this example, the update_value function uses the global keyword to explicitly declare the 'n' variable as being in the global scope. This allows the function to modify the 'num' variable in the caller's scope. When we print the value of num after calling the update_value function, we see that it has been updated to 6.
*Note that using the global keyword can make your code more difficult to read and maintain, so it should be used with caution. In most cases, it's better to use a return value or a mutable object (like a list or a dictionary) to pass information back to the caller instead of modifying a variable in the caller's scope.
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.