2
votes

Why does print(squared) return 0 instead of 100?

I thought that after being returned from the function - the value of the variable squared would be assigned to the the global variable with the same name?

squared = 0
def square(n):
    """Returns the square of a number."""
    squared = n**2
    print "%d squared is %d." % (n, squared)
    return squared


square(10)
print(squared)

returns:

enter image description here

4
You need to declare it global, otherwise you're creating a new name squared in the scope of the square function. - Peter Wood
Why would you expect it to be 100? What's the point of a function then, functions provide local scope. - Ashwini Chaudhary
@Ashwini well it would be 100 until the function is called again with another n. - ruben_KAI
@RubenBaden Stop! You have learned the wrong thing here! Do not abuse global scope because you do not understand scope. Read an introductory material that explains scope. It is there for a reason. - Two-Bit Alchemist
That's not how return works-- the name of the variable you return is irrelevant. You must assign the returned value. (Your question mixed scope and return, hence you're getting two sets of answers...) - alexis

4 Answers

5
votes

Assign the result of the function to the variable:

squared = square(10)

This is the whole point of using return squared in the function, isn't it?

3
votes

The function square never changes the variable squared that is found in the global scope. Inside the function you declare a local variable with the same name as the global variable, this however will change the local variable and not the global variable. Then when you print(squared) you are printing that unchanged global variable which is still 0 as you initially set it. As a matter of code cleanliness you really should try to avoid having local variables and global variables sharing the same name as it causes confusion (as we have seen in this question) and makes the code much harder to read.

To change the global variable from within a function you must tell Python to do so by using the global keyword to make the name refer to the global variable. You might want to look at this question: Use of "global" keyword in Python

The easier and better option of course is just to use the return value of the function. Minimizing the use of global mutable state is a good goal.

1
votes

Essentially what is happening here is you are creating a local variable in the square function. To change squared, simply type:

squared =square(10)
print squared
-1
votes

Sort of. Your very close. You need to change the following:

def square(n):
    """Returns the square of a number."""
    squared = n**2

To:

def square(n):
    """Returns the square of a number."""
    global squared

    squared = n**2

Hope this helps!