How does Python know I want to double number I did not define? (Beginner)

Viewed 97
x = 10
def double(y):
    return 2 * x
print(double(x))

Output is 20 As far as I know, it should return None because in function "double" I double x which is undefined that block.

2 Answers

x is defined outside of the function scope as a global variable that is also available in the function

It is because x is a global variable, so when you call double it is just multiplying x by 2 no matter what if you were to say put

x = 10
def double(y):
    return 2 * x
print(double(40))

you would still get 20 as you are returning the variable x multiplied by 2.

Related