Help with Global/Coerced Variable (Understanding Scope) - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Help with Global/Coerced Variable (Understanding Scope) (/thread-23624.html) |
Help with Global/Coerced Variable (Understanding Scope) - Rev2k - Jan-09-2020 Hi, I'm going through the python in easy steps book and have hit a snag with global/coerced variables. I've copied the code exactly from the book but not getting the return I expect. Here is the code: global_var = 1 def my_vars(): print( "Global Variable:" , global_var ) local_var = 2 print( "Local Variable:" , local_var ) global inner_var inner_var = 3 my_vars() print( "Coerced Global:" , inner_var )This is what I get back when I run it: What I should be getting back is:Global Variable: 1 Local Variable: 2 Coerced Variable 3 Any ideas as I've copied this exactly from the book. Thanks in advance RE: Help with Global/Coerced Variable (Understanding Scope) - ichabod801 - Jan-09-2020 You need to call the function. Add this line to the end: my_vars() RE: Help with Global/Coerced Variable (Understanding Scope) - Rev2k - Jan-09-2020 Thx for the reply ich - I'm now getting this back(not even the full return as it goes on forver and is too large to post):
RE: Help with Global/Coerced Variable (Understanding Scope) - ichabod801 - Jan-09-2020 Show your modified code. The line I asked you to add should not be indented. RE: Help with Global/Coerced Variable (Understanding Scope) - Rev2k - Jan-09-2020 modified code: global_var = 1 def my_vars(): print( "Global Variable:" , global_var ) local_var = 2 print( "Local Variable:" , local_var ) global inner_var inner_var = 3 my_vars() print( "Coerced Global:" , inner_var ) my_vars() RE: Help with Global/Coerced Variable (Understanding Scope) - sandeep_ganga - Jan-09-2020 I think you shouldnt be calling my_vars() inside the definition, that is which causing the loop. global_var = 1 def my_vars(): print( "Global Variable:" , global_var ) local_var = 2 print( "Local Variable:" , local_var ) global inner_var inner_var = 3 #my_vars() print( "Coerced Global:" , inner_var ) my_vars() Best Reegards,Sandeep GANGA SANDEEP KUMAR RE: Help with Global/Coerced Variable (Understanding Scope) - Rev2k - Jan-09-2020 Thank you so much for solving my issue, both of you. |