Writing Your Own Functions · practice
Local Variables and Scope
A
Its
def make_status(place):
message = f"Trip to {place}"
return message
Both place and message are local names. They are available while make_status is running. After the call ends, the returned
current = make_status("Seoul")
print(current) # Trip to Seoul
print(message) # NameError
current receives the
The same name can exist in different scopes
Visible evidence is better than a rule to memorize:
The make_status creates a local status. It does not replace the top-level status.
The output proves that there are two separate names:
Inside: Trip to Seoul
Returned: Trip to Seoul
Outside: Not started

When the call ends, the local status disappears. The top-level status is still "Not started".
Parameters are local too
In this function, place is created for each call:
def make_status(place):
status = f"Trip to {place}"
return status
Calling make_status("Seoul") gives the local place the value "Seoul". A later call with "Lagos" gets its own run and its own local values.
This isolation is helpful. A function can use clear temporary names without filling the rest of the program with them.
Pass information in, return information out
For now, use this reliable pattern:
def make_status(place):
status = f"Trip to {place}"
return status
current = make_status("Seoul")
Parameters pass needed information in.
Local variables hold temporary work.
passes a result out.
Python has ways to reach and change names outside a function, but a beginner program is usually easier to understand when information crosses the boundary explicitly.
What is the final line printed by this program?
label = "OUTSIDE"
def make_label():
label = "INSIDE"
return label
result = make_label()
print(result)
print(label)
Task
Complete make_status(place).
Inside the
create a
named status;give it the
Trip tofollowed byplace;return that local value.
Do not change the top-level status.
Expected output:
Trip to Seoul
Not started
After it passes, use Step in the exercise editor. Watch the local status appear during the call. After current_status receive its value while the outside status remains unchanged.