Python 3.10: Why does changing a global variable inside a nested function not affect the outer scope?
I'm working on a project and hit a roadblock. I'm working on a script in Python 3.10 where I have a nested function that modifies a global variable. However, I'm struggling to see the changes reflected in the outer scope. Here's the snippet of code I'm using: ```python x = 10 # Global variable def outer_function(): def inner_function(): global x x = 20 # Attempting to modify global variable inner_function() outer_function() print(x) # Expected output: 20 ``` To my surprise, when I run this code, I receive an output of `20` as expected, but when I added a conditional check to update the variable only when it's equal to `10`, it stopped working. Here's the modified version: ```python x = 10 def outer_function(): def inner_function(): global x if x == 10: x = 20 # Should modify x only if it's 10 inner_function() outer_function() print(x) # Expected output: 20 ``` Now, after executing this code, I get an output of `10`. I read that the use of the `global` keyword should allow the inner function to modify the global variable, so I'm confused as to why this doesn't work as expected when I include the condition. Is there something I'm misunderstanding about the scope and behavior of `global` variables in Python, especially within nested functions? Any insight would be greatly appreciated. Thanks for your help in advance!