Local Variables
Inside a function, you can create variables, just like anywhere else. But such a variable exists only inside the function: it's created when the function runs and disappears when the function ends. Outside the function, Python doesn't know it:
def greet():
message = "Hello!"
print(message)
greet()
print(message)This prints:
Hello!
Traceback (most recent call last):
File "<exec>", line 6, in <module>
NameError: name 'message' is not definedThe call greet() worked, but the last line looks for message outside the function, where it doesn't exist. Parameters are the same: they exist only inside their function.
The part of a program where a variable exists is called its scope. A variable created inside a function is local: it belongs only to that function. A variable created outside all functions can be used everywhere in the program, inside functions too:
shop_name = "Pet Corner"
def print_label(product):
print(f"{shop_name}: {product}")
print_label("dog food")This prints:
Pet Corner: dog foodWhy is it useful that local variables stay inside their functions?
- Functions don't get in each other's way. Two functions can each have a variable named
total, and those are two different variables: changing one doesn't change the other. - To use a function, you only need to know what to give it (the arguments) and what it gives back (the return value). How it works inside is its own business.
- Every call starts afresh: the variables of the function are created again, with nothing left over from the previous call.
A function can read a variable from outside, but it can't simply change it. When you assign a value to a variable inside a function, Python creates a new local variable, even if there's one with the same name outside:
score = 10
def reset_score():
score = 0
reset_score()
print(score)This prints:
10The function created its own local score and set it to 0, but the score outside stayed 10. (And score += 1 inside the function would even end with an error, UnboundLocalError.)
So the rule is simple: values go into a function through its parameters, and come out with return. When you need a value from inside a function, don't reach for its variable. Return the value and store it where you call the function.
Instructions
The program ends with the error NameError: name 'total' is not defined, because total exists only inside the function. Fix it: return total from the function. Below the function, store the result of the call total_price(25, 4) in a variable bill, and print bill instead of total. The program prints 100.
Every order costs an extra 5 for delivery. Give the function a third parameter, delivery, with the default value 5, and add it to the total inside the function. The program then prints 105.
Start programming for free
8/10