liveBook · Manning

Local variable

As explained in A Pythonic Adventure: From Python basics to a working web app

A local variable is a variable whose visibility is restricted to the function or block where it is defined.

A local variable belongs to the function where it is created. Think of it as a little note kept inside one room: code outside that function cannot see it directly. section 3.0

The menu’s private answer

In a coffee-shop menu function, choice and answer are local variables. The function can use them to turn the customer’s number into a drink, but the main program cannot print answer directly. Returning answer passes its value outside, where drink = menu(drinks, ...) stores it in a separate variable. section 3.0 section 5.1

def menu(choices, title, prompt):
    print(title)
    print("--------------------------------")
    i = 1
    for c in choices:
        print(i, c)
        i = i + 1
    choice = input(prompt)
    answer = choices[int(choice) - 1]
 
    return answer

Follow choice and answer inside the menu function, then see answer leave through return. section 3.0

Keep these points in mind:

  • Define the variable inside the function that needs it. section 3.0
  • Use return when the main program needs the value. section 5.1

How A Pythonic Adventure: From Python basics to a working web app covers it

How deep it goes
Explains function-local visibility through a menu example and return statements, without descending into execution internals.
Examples
Uses choice and answer in a reusable coffee-shop menu function.
What it assumes
Assumes basic variables and function definitions while clarifying how function scope separates local and main-program names.
What you can do after
Build it from scratch by keeping temporary values inside functions and returning values needed elsewhere.
How it connects
Connects local variables with functions, arguments, return statements, and variables in the main program.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of A Pythonic Adventure: From Python basics to a working web app. The section links point to the parts of the book it draws on.