0%

Writing Your Own Functions · practice

Local Variables and Scope

A creates a small working area for its . A variable assigned inside a function is normally local to that function.

Its is the part of the program where the name is available.

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 can live on, but those local names are no longer available to the caller.

current = make_status("Seoul")
print(current)   # Trip to Seoul
print(message)   # NameError

current receives the . It does not receive the local variable itself.

The same name can exist in different scopes

Visible evidence is better than a rule to memorize:

Try it

The inside 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
The outside and function scopes each have a separate status variable, while the function returns only its value into current.

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 :

  1. create a named status;

  2. give it the Trip to followed by place;

  3. 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 , watch current_status receive its value while the outside status remains unchanged.