Member-only story
Learning Python With Program Templates: The Input One, Process One Template
A fun way to implement loops in your programs
In previous articles, I’ve discussed program templates for entering data, entering, processing, and outputting data, and making decisions in programs by selecting from alternatives. In this article, I’ll discuss a program template for writing programs that receive data input and then process that data before moving on to new data.
This template is called Input One, Process One. This template should be used when your program cannot receive all the data before performing processing or when you just want the program to input and process data elements one at a time.
You can compare this template with an earlier template we looked at: Input, Process, Output. This template is used when you want to get all the data into your program before performing any processing and output. With the Input One, Process One template, output happens during the processing step.
The Input One, Process One template is implemented using a looping statement. I will demonstrate the template using Python’s for
statement and in a separate article that discusses implementing a different template, I’ll cover Python’s while statement for implementing loops.
The for Statement
The for
statement is a looping construct that instructs a program to repeat a set of programming instructions a set number of times. There are several ways to write for statements in Python. I’ll start by showing you one syntax template:
for var in range(start, end):
do something
This syntax template uses the built-in range
function. This function allows you to specify a range of numbers that represent the number of iterations (loops, or executions) you want with the for statement. For example, if I want the for
statement to iterate ten times, I can use the range (1,11)
. Even though I want only ten iterations, I have to specify 11
as the stopping point of the range.
Now, let’s look at how the for
statement works. This first example prints the numbers 1 through 10:
for i in range(1, 11):
print(i)