How Can Loops Manipulate Python’s Print Function?

The Python print function can use loops to simplify code and create interesting designs.

Imagine you want to create a table that has a recurring mathematical sequence:

Say you want to demonstrate simple addition:

You could use a print function for each line, but that’s a bit inefficient! That’s six lines of code. Why not do it in 2? There’s an obvious pattern. The number starts at 0 and counts until 5.

repeat 6 times

  • 1 + x
  • add 1 to x

That’s a lot shorter than 6 lines!

KISS

One of the first acronyms I teach my students is KISS:

The trick to programming well is to look for repetitive lines of code, and see if you can make it shorter by adding a loop or some other structure. Share on X

Using Python Print Function with Loops

The for loop is Python’s counting loop. It can be used to keep track of the number of repetitions.

One way to find errors is by tracing the loop values to ensure that the logic is right:

for x in range (0, 6)

xx + 1
01
12
23
34
45
5stop

The x variable counts from 0 to 6 by adding 1 each time the loop repeats.  The loop stops when it reaches the last value.

Python Print Function with Loops Tip!

Do the trace first before you code. That way, you can see how the values are changing, which will help you write the for loop range!

The Importance of Loops

A loop contains a sequence of events in a specific order.  Understanding how a sequence works is an important step in coding so practising can help a new coder:

I have a resource if you’re interested in teaching the Python print function with loops. It includes answer keys as well as lessons with teacher notes.

python-print-function-with-for-loops-resource

You can also buy the full unit (which includes two tests) here.

python-graphics-and-for-loops-unit2

This unit includes Online Learning slides with embedded videos that can be used in Google Classroom on Microsoft One Drive, as well as a zipped PDF file with slides, answer keys, rubrics and code exemplars.

More Ideas!

Looping print output can be fun, but find out what happens when you loop graphics!

More Resources