points = 0
def testfunction():
points = 2
return points
testfunction()
print (points)
Why does the points now not equal 2?
points = 0
def testfunction():
points = 2
return points
testfunction()
print (points)
Why does the points now not equal 2?
Here, testFunction
creating another points
variable in its local scope. That's why the the value of global points
variable not changed. You need to tell your function that you want to use the global points
variable,
points = 0
def test_function():
global points
points = 2
return points
test_function()
print(points)
Or you can assign the return value to the points
variable, like:
def test_function():
points = 2
return points
points = test_function()
print(points)
And most of the Pythonistas prefer snake_casing for naming functions and variables.
the return
from a function must be assigned to a variable. you can edit a global variablelike this:
points = 0
def test_function():
global points
points = 2
pass
test_function()
print(points)
Or without calling points as a global variable:
points = 0
def testfunction():
points = 2
return points
points = testfunction()
print (points)
obviously this does make the initial declaration of points
rather obsolete...
You have two different variables with the name points
. One is declared in the outer scope and the other is local to the function testfunction()
.
The outer scope points
variable is set to 0 and never updated. The local scope points
is set to 2
, returned from the function, and then evaporates into oblivion. The value that is returned by the function is essentially "spit out" to the left, and is available for assignment to another variable.
Thus:
points = 0
def testfunction():
points = 2
return points
points = testfunction()
print (points)
will accomplish what you want.
It might be clearer to write this as:
calc_result = 0
def testfunction():
points = 2
return points
calc_result = testfunction()
print (calc_result )
Also, because Python does not require any kind of variable declaration, the first line is not needed.
A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.
So you can't modify from your function the outside variable even they have the same name.
You can use:
points = testfunction()