Concepts / The Print Function

The Print Function

The print function is one of the most fundamental tools in Python.

  • Programming
Interactive lab

Try it: Scope: Local, Enclosing, Global, Built-in

How Python looks up a name Local → Enclosing → Global → Built-in, why assigning to a name inside a function makes it local (and raises UnboundLocalError if it is read first), and what global, nonlocal and closures change.

How it works

  1. Before a function runs, Python marks every name assigned inside it as local to that function, unless it is declared global or nonlocal.
  2. Reading a name searches the local namespace, then enclosing functions, then the module's globals, then the built-ins; the first hit wins.
  3. A local name read before it has a value raises UnboundLocalError (Python does not fall back to the global).
  4. global x makes assignments go to the module namespace; nonlocal x makes them go to the nearest enclosing function.
  5. A function's local frame disappears when it returns, unless an inner function (a closure) still uses its variables.

Default run (10 steps): Ready: Local shadows global. Every name is looked up Local, then Enclosing, then Global, then Built-in. … Finished. Printed: inside: 99 / outside: 10.

Simplified: The lab's own small Python interpreter runs a fixed, hand-written script (you choose the variant and the values, never the code); nothing is executed as real Python. Every script was run in CPython 3.12 with the same inputs and the lab reproduces its output and error messages. Built-ins shows only the names the script used.

Educational simulation

Loading the simulation…

What Print Does

The print function is one of the most fundamental tools in Python. Its job is simple: take whatever you give it and display that information on the screen. When you write print('hello world'), Python sends the text 'hello world' to your output, and you see it appear. Print doesn't change your data, doesn't store anything for later, and doesn't do any computation—it just shows you what you ask it to show.

Think of print as a messenger. You hand it a message, and it delivers that message to your screen. Every time you call print, a new line of output appears. This makes print invaluable for understanding what your code is doing at each step.

Defining Versus Calling

A critical distinction in programming is the difference between defining a function and calling it. When you write def say_hello():, you are telling Python what the function should do—you are creating a blueprint. The code inside the function does not run at that moment. It only runs when you actually call the function by writing say_hello().

Definition creates the blueprint. Call executes the blueprint. Until you call the function, the code inside it sits dormant. This separation is essential because it lets you define a function once and then use it many times without rewriting the code.

Python reads yourcodedef say_hello():print('hello world')stored, not executed yetFunction definitioncompletesay_hello()first callprint('hello world')runssay_hello()second callprint('hello world')runs againencounters definitionreads function bodystores blueprintencounters first callexecutes function bodyencounters second callexecutes function body again
What happens when you define a function versus when you call it? In what order do the lines execute?

How Indentation Marks Function Boundaries

In Python, indentation is not just for readability—it is the syntax rule that determines which lines belong inside a function and which are outside. Every line indented under the def line is part of the function's body. The moment you return to the original indentation level, you have exited the function.

def say_hello():function definition startsprint('hello world')indented = inside functionsay_hello()no indent = outsidefunctionsay_hello()no indent = outsidefunction
Which lines belong inside the function and which are outside? How does indentation determine what's part of the function?
python

Tracing Execution with Print

Let's trace through what happens when Python runs the code above. First, Python reads the def line and stores the blueprint for say_hello. It does not execute print('hello world') yet. Then Python encounters the first say_hello() call. Now it jumps into the function, executes print('hello world'), and the text appears on screen. Then Python returns to where it was and encounters the second say_hello() call. It jumps into the function again, executes print('hello world') a second time, and returns.

Output
hello world
hello world

The output shows two lines because print was called twice. Each call to say_hello() caused the function body to run, and each execution of print('hello world') produced one line of output.

Print with Parameters and Local Scope

Print becomes more powerful when combined with function parameters. You can pass values into a function and then print them. This is where understanding scope becomes important. When you define a variable inside a function, it exists only within that function. When you use print to display it, you are showing the local value, not affecting any variable with the same name outside the function.

Worked example

Print with Local Variables

Define a function called print_max that takes two parameters, a and b, and prints the larger of the two numbers.

  1. 1
    Define the function with two parameters

    Write def print_max(a, b): to create a function that accepts two inputs.

  2. 2
    Use an if statement to find the larger value

    Inside the function, check if a > b. If true, the larger value is a. Otherwise, it is b.

  3. 3
    Print the result

    Use print to display the larger number. The print function will show the value stored in the local variable.

  4. 4
    Call the function with different values

    Call print_max(5, 3) and print_max(10, 8) to see print display different results each time.

Result

Each call to print_max produces one line of output showing the larger of the two numbers passed in.

python
Output (expected)
5
10

Global Variables and Print

When you define a variable outside any function, it is a global variable. A function can read a global variable and print its value. However, if you assign a new value to a variable inside a function, Python treats that as a local variable, separate from the global one. This is an important distinction because it affects what print displays.

python
Output (expected)
5
10
5

In this example, the first print inside show_x() displays 5 because it reads the global x. The second print displays 10 because the assignment x = 10 created a local variable. After the function returns, the final print displays 5 again, confirming that the global x was never changed by the function.

Common Mistakes with Print

  • Common mistake

    Forgetting that defining a function does not execute it

    What it looks like

    Writing def say_hello(): print('hello') and then expecting output without calling say_hello()

    Why it fails

    The def line only creates the blueprint. Python does not run the code inside until you call the function.

    Do this instead

    Always call the function: say_hello(). Without the parentheses and call, the function body never runs.

  • Common mistake

    Confusing print output with variable assignment

    What it looks like
    Writing x = print('5') and then expecting x to be 5
    Why it fails

    print() displays text but returns None. The variable x becomes None, not 5.

    Do this instead

    If you need to store a value, assign it directly: x = 5. Use print only to display values, not to create them.

  • Common mistake

    Assuming a local variable inside a function affects the global variable with the same name

    What it looks like

    Defining x = 5 globally, then inside a function writing x = 10, and expecting the global x to change

    Why it fails

    Assignment inside a function creates a local variable. The global x remains unchanged.

    Do this instead

    If you need to modify a global variable from inside a function, use the global keyword: global x; x = 10.

  • Common mistake

    Printing before defining a variable

    What it looks like

    Writing print(y) before y is assigned any value

    Why it fails

    Python will raise a NameError because y does not exist yet.

    Do this instead

    Always define a variable before printing it: y = 5; print(y).

When to Use Print for Debugging

Print is a powerful debugging tool. When your code is not behaving as expected, add print statements to see what values your variables hold at different points. This helps you trace the execution and spot where things go wrong.

Best practice

Place print statements at key moments: right after a variable is assigned, before and after a function call, and inside conditional blocks to see which branch executes. This creates a trail of output that shows you exactly what your program is doing.

python
Output (expected)
Entered calculate_total with price = 10 and quantity = 5
Calculated total = 50
Final result = 50

The print statements here show you the values entering the function, the intermediate calculation, and the final result. This makes it easy to verify that each step is working correctly.

Practice

EASY

Write a function called greet that takes one parameter, name, and prints a greeting message that includes that name. Call the function three times with different names and observe the output.

Hints
  • Use def greet(name): to define the function.
  • Inside the function, use print to display a message that includes the name parameter.
  • Call greet('Alice'), greet('Bob'), and greet('Charlie') to test it.
MEDIUM

Define a global variable called counter set to 0. Create a function that prints the current value of counter, then increments it by 1. Call the function three times and explain what you see in the output. Why does counter not increase after the function returns?

Hints
  • Remember that assignment inside a function creates a local variable unless you use the global keyword.
  • Print counter before and after incrementing it inside the function.
  • After the function returns, print the global counter to see if it changed.

Summary

  1. 1
    The print function sends output to the screen. It does not modify data or store values—it only displays them.
  2. 2
    Defining a function with def creates a blueprint. The code inside does not run until you call the function by writing its name with parentheses.
  3. 3
    Indentation determines which lines belong inside a function. Lines indented under def are part of the function body; lines at the original indentation level are outside.
  4. 4
    Functions can have parameters and local variables. Print can display these local values without affecting global variables with the same name.
  5. 5
    Use print statements strategically during debugging to trace your program's execution and verify that variables hold the values you expect.

At a glance

  • The print function displays output on the screen without modifying data or storing values.
  • Defining a function with def is different from calling it—definition creates a blueprint, and calling executes the code inside.
  • Indentation in Python determines which lines belong inside a function and which are outside.
  • Functions can use local variables and parameters; print displays these without affecting global variables of the same name.
  • Print is a valuable debugging tool for tracing program execution and verifying variable values at key points.

Related concepts

More concepts starting with T