Course 5.2Lesson 4 of 6
A variable made inside a function is local: it lives only while the function runs, and Python does not know its name outside, so using it there gives a NameError. To get a result out, return it. A function can read a variable from outside, but if it assigns to the same name, it makes a new local variable and the outside one stays. Parameters are local variables too. Rely on parameters and return, and not on outside variables, so that a function works alone and is easy to test.
Try the code and the simulations beside the lesson.
After this lesson you can
NameError for a variable inside a function,When a function runs, Python makes a small private room for it. The variables that you make inside are in that room. When the function ends, the room is closed, and the variables disappear. This is called local scope. Variables made outside any function are in the open space of the program, the global scope.
The same is true of parameters. name in make_greeting(name) is a local variable too.
What if the outside program and a function use the same name?
Now the second part. A function can read a variable from outside. The function add_tax uses rate without making one, so Python looks outside and finds it. But this is a risk. If someone changes rate later, the function gives a different answer for the same argument, and the reason is not in the function. A beginner is surprised.
To get a value out of a function, return it, and store the answer: x = change().
Make a function depend on its parameters only, and give its result with return. Then
Pass the tax rate as a parameter: def add_tax(price, rate):. The call is then a little longer, but the function has no hidden inputs.
Python has a word, global, to let a function change an outside variable. You will meet it in other people's programs. It is better to avoid it, for the same reason: a function that changes things outside is hard to follow. Return the new value, and let the caller store it.
A function is a room with a door. What goes in comes through the parameters (the door). What comes out goes through return (the door again). Nothing passes through the walls.
NameError.global for convenience.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
NameError.return out.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
message live in the first program of this lesson?x = 10 and a function that sets x = 99 inside, what is the outside x?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.