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.
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.
Subscribe to be the first to know when a new Python course is released.