Back Python Chrestomathics Ahead |
Part 8 — Looping
We are humankind — What a mantra that should be — I’m human and kind
Did you not expect – The repetition to come – Did you not expect
Section 8.1: Why it’s necessary
- Up to this point, every action we wanted to take required its own statement.
- That limitation is not sustainable if we need to process big amounts of data or even small amounts of data whose size is not known until the program runs.
- We need programs to be flexible — to be able to handle differing amounts of inputs and outputs.
- To support such problem solving, Python provides the
for
andwhile
statements. FYI: bothfor
andwhile
are keywords.
- The
for
andwhile
statements have the ability to repeatedly execute code. The fancy word for this is iteration, the everyday word is looping. In this part, we explore thefor
loop.
Section 8.2: For loop — first contact
- Even though I am a reluctant pessimist by nature, I like to think that you carefully read all of our documentation. This time is one of those times when it is especially important to do so. Why not read this part several times.
- We start with an example, where the user is asked to supply a list of words. The example comes from first_contact.py.
reply = input( "Enter text: " )
words = reply.split()
- Suppose in reaction to the prompt, the user supplies
Enter text: eat a peach
- If that is the case then variables
reply
andwords
look like
reply: eat a peach
words: ['eat', 'a', 'peach']
- The first loop in the program processes the characters in
reply
one-by-one. Immediately after the loop is an emptyprint()
statement to separate its output from what follows.
# print the characters in the reply one by one
print( "reply: character by character" )
for character in reply :
print( character )
print()
- Following keyword
for
is the loop variable, which is in this casecharacter
. There is nothing magical about the namecharacter
. It could have been any legal identifier. The name is a good one, because of the role it plays in the loop.
- Following the loop variable is the keyword
in
. This keyword is a visual separator of the loop variable and the sequence of values to be processed.
- The sequence to be processed in this case is the string
reply
. When the sequence is a string, the loop variable will take on each character in the string one-by-one.
- The last part of a loop is called the body of the loop. It is the actions that the loop executes once for each value assigned to the loop variable. Python requires the body of the loop to be indented. Because the empty
print()
statement is not indented, it is not part of the loop. So, the body of this loop is just the statement
print( character )
- The code segment dispays
reply: character by character
e
a
t
a
p
e
a
c
h
words: word by word
eat
a
peach
print( "reply:", reply )
print( "words:", words )
8.X What’s next
- TBD