-4
def f():
    global s
    print s
    s = "That's clear."
    print s     

s = "Python is great!" 
f()
print s

Output:

Python is great!
That's clear.
That's clear.

as per program, the last print statement should return "s= Python is great" because I think here S should be referred Global variable.

3
  • It is, but you gave it a new value in f(). Globals can be accessed and modified in any scope. If you want the last print to output "Python is great", then you should not declare s a global. Commented Jul 13, 2017 at 10:26
  • No, you just updated it in your function. It would still be "Python is great!" if you hadn't declared it as global in f. Commented Jul 13, 2017 at 10:26
  • You have changed the value of global variable 's' in the function 'f()' Commented Jul 13, 2017 at 10:36

2 Answers 2

2

You modified the global variable in your function (f) so the variable now has the value that you modified at last i.e. "That's clear."

Sign up to request clarification or add additional context in comments.

Comments

0

The output is correct. After s is defined as a global variable, you print the value assigned to s at that point which is Python is great, then you assign That's clear. to s - s is now global, so when you assign That's clear. to it inside your function, that becomes it's value in the outer scope as well.

Here is a good stackoverflow answer regarding Scoping Rules.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.