Python/For Statement

Objective

Books-aj.svg aj ashton 01f.png
  • Learn about Python's iterator-based loop statement, for.
  • Learn about three dependent statements, else, break, and continue.

Page Index

Lesson

The For Statement

Even though the while statement is great for recursive loops, it isn't good for iterator-based, recursive loops. This is where the for statement comes in. The for statement loops are based on a collection of items, putting each item into a temporary variable for use. We'll also need to use the in statement for syntactic sugar as demonstrated below.

>>> for spam in ("A", "B", "C", "D", "..."):
...     print(spam)
...
A
B
C
D
...

As you can see, the temporary variable that holds the item from a sequence or collection follows the for statement. In this case, spam is the temporary variable. After that, the in statement is required, followed by the sequence or collection.

The way for is used in Python and C-based languages differs significantly. Since Python's for statement is iterator-based, how would we have the temporary variable hold a number that increments on every loop? You could make a large tuple to hold each number, but this would waste a lot of memory and time. The built-in function range can help us here. This function creates an iterator list of numbers, without all the typing or memory waste. There's an example below demonstrating the uses of range.

>>> for orange in range(10):
...     print(orange)
...
0
1
2
3
4
5
6
7
8
9
>>> for juice in range(2, 10):
...     print(juice)
...
2
3
4
5
6
7
8
9

The range function itself is a bit advanced, so I showed its two most basic forms. When only one parameter is used, the new range is from 0 and stops at the parameter. In the case of range(10), the range is from 0 to 9.

The second example uses two parameters, the first is the number to start from, instead of a default 0. The second parameter is the number to stop. So like the example, range(2, 10) is 2 to 9.

A little follow up on the range function. Although this function creates an iterator list, it isn't an iterator by itself. The range function is actually called a generator. A generator is an object that creates a group of iterator items when needed. Since they do this, their iterator lists are temporary; they do not stay in the computer's memory forever.

The Else Statement

Much like the while statement, the for statement's else is executed if the loop doesn't end prematurely for any reason: errors, special keyboard keys, other statements, et cetera. A brief example is given below.

>>> for blue in (1, 2, 3, 4, 5, 6, 7):
...     print(blue % 2)
... else:
...     print("The for loop was a success!")
...
1
0
1
0
1
0
1
The for loop was a success!

The Break Statement

The break statement works the same for the for statement as it did with the while statement. It will completely end the loop prematurely, which might be helpful in some cases. Again, another brief example is given below.

>>> for berry in (1, 2, 3, 4, 5, 6, 7, 8):
...     print(berry % 4)
...     if berry % 4 == 0:
...         break
... else:
...     print("The for loop didn't end prematurely!")
...
1
2
3
0

The Continue Statement

The continue statement acts just like it does with the while statement. It will stop the current execution of code and go back to the beginning of the loop. A short example is given below.

>>> for eggs in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10):
...     if eggs % 2 == 0:
...         continue
...     print(eggs % 2)
...
1
1
1
1
1


To summarize from the previous lesson, the continue statement can be used to increase readability and reduce large amounts of indentation.



Examples of for loops


Print location and contents of each position in a list:

a = [0,1,-2,3,-4,-5,-6,-7,8,-9,10,11,-12]

for p,c in zip(range(len(a)), a) :
    print ('a[{}] = {}'. format(p,c))

a[0] = 0

a[1] = 1

a[2] = -2

a[3] = 3

a[4] = -4

a[5] = -5

a[6] = -6

a[7] = -7

a[8] = 8

a[9] = -9

a[10] = 10

a[11] = 11

a[12] = -12

or:

a = [0,1,-2,3,-4,-5,-6,-7,8,-9,10,11,-12]

p = 0
for c in a :
    print ('a[{}] = {}'. format(p,c))
    p += 1

Output is same as that above.


zip is not limited to two inputs:

names =['John', 'Bill', 'Jack']
ages = [21, 30, 45]
weights = [165, 132, 175]
heights = [[5,8], [4,1], [6,1]]

for name, age, weight, height in zip(names, ages, weights, heights) :
    feet, inches = height
    print ( "{}: age = {} years; weight = {} lbs; height = {} ft {} in".
                    format(name, age, weight, feet, inches) )

John: age = 21 years; weight = 165 lbs; height = 5 ft 8 in

Bill: age = 30 years; weight = 132 lbs; height = 4 ft 1 in

Jack: age = 45 years; weight = 175 lbs; height = 6 ft 1 in


Remove all negative numbers from the list:

a = [0,1,-2,3,-4,-5,-6,-7,8,-9,10,11,-12]

b = list(range(len(a)-1, -1, -1))
print ('b =', b)

for p in b :
    if a[p] < 0 : del a[p]

print ('a =', a)

b = [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

a = [0, 1, 3, 8, 10, 11]


Assignments

Crystal Clear app kedit.svg
  • Work with the for statement and get a general feeling of how it works.
  • Test the for statement with tuples, lists, sets, and dictionaries. See how they compare and find differences between them.
Sweden road sign A10.svg Completion status: Ready for testing by learners and teachers. Please begin!


References


1.WikiVersity:

Previous lesson "Dictionaries#An_elementary_database" for examples of for loops.


2. Python's documentation:

"8.3. The for statement", "4.4. break and continue Statements, and else Clauses on Loops", "4.6.6. Ranges", "5.6. Looping Techniques", "7.9. The break statement", "7.10. The continue statement"


3. Python's methods:


4. Python's built-in functions:


  This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.


Python/For_Statement
 

Manage research, learning and skills at IT1me. Create an account using LinkedIn to manage and organize your IT knowledge. IT1me works like a shopping cart for information -- helping you to save, discuss and share.


  Contact Us  |  About IT1me.com |  IT Training & References |  IT Careers |  IT Hardware |  IT Software |  IT Books