Python Forum

Full Version: Help with Global/Coerced Variable (Understanding Scope)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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:

Error:
C:\Users\rev\PycharmProjects\untitled1\venv\Scripts\python.exe C:/MyScripts/scope.py Process finished with exit code 0
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 Smile
You need to call the function. Add this line to the end:

my_vars()
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):

Error:
Global Variable: 1 Local Variable: 2 Global Variable: 1 Local Variable: 2 Traceback (most recent call last): File "C:/MyScripts/scope.py", line 14, in <module> my_vars() File "C:/MyScripts/scope.py", line 11, in my_vars my_vars() File "C:/MyScripts/scope.py", line 11, in my_vars my_vars() File "C:/MyScripts/scope.py", line 11, in my_vars my_vars() [Previous line repeated 993 more times] File "C:/MyScripts/scope.py", line 3, in my_vars print( "Global Variable:" , global_var ) RecursionError: maximum recursion depth exceeded while calling a Python object Global Variable: 1 Local Variable: 2 Global Variable: 1 Local Variable: 2 Global Variable: 1 Local Variable: 2 Global Variable: 1 Local Variable: 2 Global Variable: 1 Local Variable: 2 Global Variable: 1 Local Variable: 2 Process finished with exit code 1
Show your modified code. The line I asked you to add should not be indented.
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()
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()
Output:
python test4.py Global Variable: 1 Local Variable: 2 Coerced Global: 3
Best Reegards,
Sandeep

GANGA SANDEEP KUMAR
Thank you so much for solving my issue, both of you.