Local variables
The scope of a variable is the part of the program where the variable can be used. Variables created inside a function, its parameters included, are local to that function: they exist only inside it, and only while it runs. When the function returns, they are gone:
def greet(name):
message = f"Hello, {name}!"
print(message)
greet("Ada")
print(message)
Hello, Ada!Traceback (most recent call last):
File "main.py", line 7, in <module>
print(message)
^^^^^^^
NameError: name 'message' is not definedThe function printed its greeting, but outside the function there is no variable message. The same goes for the parameter name. To get a value out of a function, the function returns it, and the caller stores the return value in a variable of its own.
Same name, different variables
Because a function's variables are its own, a function can use a name that the main program also uses, and the two don't disturb each other:
def double(number):
result = number * 2
print("Inside:", result)
return result
result = 10
answer = double(4)
print("Outside:", result)
print("Answer:", answer)
Inside: 8
Outside: 10
Answer: 8There are two variables called result here: one in the main program, with the value 10, and one inside double, which exists only during the call. Setting the function's result to 8 leaves the main program's result alone. This is what makes functions safe to use: you can call a function without knowing which names it uses inside.
Each call starts afresh
Local variables are created again on every call, so they don't remember anything from the call before:
def count_visit():
visits = 0
visits += 1
print("Visits:", visits)
count_visit()
count_visit()
count_visit()
Visits: 1
Visits: 1
Visits: 1Global variables
As the module on functions showed, variables created in the main program, outside every function, are global. A function can read a global variable, and it sees the value the variable has at the moment of the call:
tax_percent = 25
def with_tax(price):
return price * (100 + tax_percent) / 100
print(with_tax(80))
tax_percent = 10
print(with_tax(80))
100.0
88.0Reading globals like this works, but the function depends on something outside it, and you saw in the module on functions how that leads to bugs. Usually it's clearer to give the function what it needs as a parameter. The next step shows what happens when a function tries to change a global variable.