global and local variables misconception
<p>I have a question regarding the output from the following code:</p>

<pre><code>def f():

     global s
     print(s)
     s = "That's clear."
     print(s)

s = "Python is great!"
f()
print(s)
</code></pre>

<p>The output is this:</p>

<blockquote>
  <p>Python is great!</p>
  
  <p>That's clear.</p>
  
  <p>That's clear.</p>
</blockquote>

<p>My question is:  Why is it the very last output (i.e. the third output) is also "That's clear" .<br>
How come the third output is not "Python is great!" . 
I thought the very last statement from the code (i.e. the print(s)) statement is outside the function f(). So shouldn't print(s) here looks at the s variable that is defined globally? in this case the globally defined variable s would refers to the value "Python is great!", isn't it?  Sorry there must be some concepts I have mis-understand. I am very newbie to python. Could someone kindly explain this simple concept. </p>

<p>To see the output you do, the structure of you code has to be:</p>

<pre><code>def f():
    global s
    print(s) # s outside the function
    s = "That's clear." # new global s created
    print(s) # print the new s

s = "Python is great!" # s before you call the function/get to s = "That's clear."
f() # f gets called and new global s is created
print(s) # you see the new global s created in the function
</code></pre>

<p>Making <em>s</em> global means you see it outside the scope of <code>f</code>, you have already executed the function by the time you reach the last print so now the  <em>s</em> points to <code>That's clear.</code></p>

<p>If you wanted to get the output you expected, you would pass s into the function and not use the global keyword so the <em>s</em> created in <code>f</code> would be  accessible only in the scope of the function itself.</p>

<pre><code>def f(s):
    print(s)
    s = "That's clear."
    print(s)

s = "Python is great!"
f(s)
print(s)
</code></pre>

<p>This should be a  good lesson on why using <em>global</em> is rarely a good idea.</p>

python global-variables