Python Concepts/For Statement

From Wikiversity
Jump to navigation Jump to search

Objective[edit | edit source]

  • Learn about Python's iterator-based loop statement, for.
  • Learn about three dependent statements, else, break, and continue.

Page Index[edit | edit source]

Lesson[edit | edit source]

The For Statement[edit | edit source]

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 its two most basic forms are shown here. 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[edit | edit source]

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[edit | edit source]

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[edit | edit source]

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[edit | edit source]


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]

Execution speed[edit | edit source]

with range()[edit | edit source]

When for is combined with range() as in the example below, speed of execution is greatly improved.

limit =	100_000_000

condition = 2
print ('condition =', condition)

while (1) :
  if (condition == 1) :
    print ('testing "for"')
    for count in range (0,limit) : pass
    break

  if (condition == 2) :
    print ('testing "while"')
    count = 0
    while (count < limit) : count += 1
    break
$ time python3.6 for.py  ;echo $?
condition = 1
testing "for"

real	0m6.946s
user	0m6.919s
sys	0m0.016s
0
$ time python3.6 for.py  ;echo $?
condition = 2
testing "while"

real	0m19.453s
user	0m19.416s
sys	0m0.023s
0
$

This example shows that the for statement is simple in concept, simple to implement and fast in execution.

Assignments[edit | edit source]

  • Work with the for statement and get a general feeling of how it works.
  • Test the for statement with strings, tuples, lists, sets, and dictionaries. See how they compare and find differences between them.

Completion status: Ready for testing by learners and teachers. Please begin!


References[edit | edit source]

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: