As an Amazon Associate we earn from qualifying purchases.
Printing is the simplest way to see what a program is doing. In Python, the print function sends text to the screen, which makes it useful for checking that code runs, for tracking values and for finding mistakes. This article shows how it works on a Raspberry Pi, using a small LED blink program where each change of the light is also printed to the terminal.
The video below walks through the example. The code that follows is a cleaned-up version of it.
What the print function does
When you call print('hello'), Python writes the text to the standard output, which on a Raspberry Pi is normally the terminal window you ran the script from. Each call ends with a new line by default, so every message appears on its own row.
You can print text, numbers and the values of variables. If you want more detail on printing strings, variables and constants, we cover it in a separate article.
The LED blink example
This program turns an LED on, waits half a second, turns it off, waits again and repeats forever. Every time the state changes, it prints a message so you can match what you see on the board with what appears on screen.
import RPi.GPIO as gpio #imports the GPIO library
import time #imports the time module
gpio.setmode(gpio.BOARD) #use physical pin numbers
gpio.setwarnings(False) #disable warnings
gpio.setup(40,gpio.OUT) #set pin 40 as an output
while True: #starts an infinite loop
gpio.output(40,1) #sets the pin high (LED on)
print('led is on')
time.sleep(.5) #waits half a second
print('led is off')
gpio.output(40,0) #sets the pin low (LED off)
time.sleep(.5) #waits half a second
Fixes compared with the older version
The earlier version of this script had one line written as print 'led is on' and another as print('led is off'). Mixing the two styles is a problem:
- Python 2 treated print as a statement, so no brackets were needed.
- Python 3 treats print as a function, so brackets are required. The old style causes a SyntaxError.
Python 2 is no longer maintained, so it is best to use the bracket form everywhere, as in the code above. The comments were also corrected: the delay is half a second, not one second, and the lines with import bring in modules rather than header files.
How the code works, step by step
- Imports.
RPi.GPIOlets Python control the pins on the Pi, andtimeprovides the delay. - Pin numbering.
gpio.BOARDmeans you refer to pins by their physical position on the header. Pin 40 is the last pin on the 40-pin header. - Setup.
gpio.setup(40, gpio.OUT)makes the pin an output so it can drive the LED. - Loop.
while Truerepeats the block until you stop the program. - Output and print. Writing 1 sets the pin high and writing 0 sets it low. The print calls report each state.
Wiring the LED safely
Connect the LED in series with a resistor between the output pin and a ground pin. The resistor limits the current so the LED and the Pi are not damaged. Resistors of a few hundred ohms are a common choice for a basic indicator LED, but check the LED’s datasheet if you are unsure. Also remember that the longer leg of an LED is usually the positive side (anode), which connects toward the GPIO pin.
Always check your wiring before you run the script, and power the Pi off while you change connections.
Stopping the program cleanly
Because the loop never ends, you stop it with Ctrl+C. That interrupts the script but leaves the pin configured. A tidier approach is to catch the interruption and release the pins:
try:
while True:
gpio.output(40,1)
print('led is on')
time.sleep(.5)
print('led is off')
gpio.output(40,0)
time.sleep(.5)
except KeyboardInterrupt:
print('stopped by user')
finally:
gpio.cleanup() #resets the pins
With gpio.cleanup() in place, you can also leave setwarnings(False) out, since the warning it hides usually appears when pins were not released after a previous run.
Tips for useful print output
- Keep messages short and specific. “led is on” is clearer than “here”.
- Print values, not just labels. For example,
print('pin', 40, 'is high')shows several items separated by spaces. - Use f-strings for readability. In Python 3.6 and later,
print(f'pin {pin} is high')inserts a variable directly into the text. - Remove or reduce prints in finished projects. Printing inside a very fast loop can flood the terminal and slow the program down.
- Consider the logging module for larger programs. It lets you switch messages on and off by level without editing every line.
Common problems
The script shows a SyntaxError on the print line
You are running Python 3 with Python 2 style code. Add brackets around what you print.
The LED does not light, but the messages appear
The code is running, so the problem is probably in the wiring. Check the LED direction, the resistor, the ground connection and that you used the pin number that matches the numbering mode (BOARD or BCM).
The script says permission denied or cannot access GPIO
Check that the RPi.GPIO library is installed and that your user has access to the GPIO. On some setups you may need to run the script with higher privileges.
Frequently asked questions
Is print a statement or a function in Python?
In Python 3 it is a function, so you write print('text'). In Python 2 it was a statement that could be written without brackets.
Can I print on the same line instead of a new one?
Yes. Python 3 lets you change the ending with print('text', end=''), which stops the new line from being added.
Does print slow down my Raspberry Pi program?
Only slightly in most cases. In a tight loop with no delay, however, heavy printing can make the program less responsive, so print less often or use logging.
What does BOARD mean in gpio.setmode?
It tells the library to use the physical pin positions on the header. The alternative, BCM, uses the chip’s own GPIO numbers instead.