0% found this document useful (0 votes)
6 views

Iteration & Range

The document discusses for loops in Python including using them to iterate over sequences like lists and strings, optional else blocks, break and continue statements, nested loops, and using the built-in range() function to generate sequences of numbers to iterate over.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Iteration & Range

The document discusses for loops in Python including using them to iterate over sequences like lists and strings, optional else blocks, break and continue statements, nested loops, and using the built-in range() function to generate sequences of numbers to iterate over.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

PROGRAMMING WITH PYTHON 3.X.

x – ITERATION & RANGE

3.THE FOR LOOP ( for Collections)


The for loop is a generic iterator in Python: it can step through the items in any
ordered sequence or other iterable object. The for statement works on strings, lists, tuples,
and other built-in iterables, as well as new user-defined objects.

for entity in collection: # Assign object items to target


statements # Repeated loop body: use target
else: # Optional else part
statements # If we didn't hit a 'break'

When Python runs a for loop, it assigns the items in the iterable object to the target one by
one and executes the loop body for each. The loop body typically uses the assignment target
(entity) to refer to the current item in the sequence as though it were a cursor stepping
through the sequence.

The name used as the assignment target in a for header line is usually a (possibly new)
variable in the scope where the for statement is coded. There’s not much unique about this
name; it can even be changed inside the loop’s body, but it will automatically be set to the
next item in the sequence when control returns to the top of the loop again.

After the loop this variable normally still refers to the last item visited, which is the last
item in the sequence unless the loop exits with a break statement.

The for statement also supports an optional else block, which works exactly as it does in a
while loop—it’s executed if the loop exits without running into a break statement (i.e., if
all items in the sequence have been visited). The break and continue statements introduced
earlier also work the same in a for loop as they do in a while. The for loop’s complete
format can be described this way:

for item in object: # Assign object items to target


statements
if test: break # Exit loop now, skip else
if test: continue # Go to top of loop now
else:
statements

As mentioned earlier, a for loop can step across any kind of sequence object.

Compiled by: Michael Devine. 8884009669


PROGRAMMING WITH PYTHON 3.X.x – ITERATION & RANGE

In our first example, for instance, we’ll assign the name x to each of the three items in a list
in turn, from left to right, and the print statement will be executed for each. Inside the print
statement (the loop body), the name x refers to the current item in the list:

>>> for x in ["spam", "eggs", "ham"]:


print(x, end=' ')

spam eggs ham

>>> for x in ["spam", "eggs", "ham"]:


for y in x:
print(x, end=' ')
print(' ')

spam spam spam spam


eggs eggs eggs eggs
ham ham ham

>>> for x in ["spam", "eggs", "ham"]:


for y in x:
print(y, end=' ')
print(' ')

spam
eggs
ham
>>>

The next two examples compute the sum and product of all the items in a list.

>>> sum = 0
>>> for x in [1, 2, 3, 4]:
sum = sum + x
>>> sum
10
>>> prod = 1
>>> for item in [1, 2, 3, 4]:
prod *= item
>>> prod
24

Compiled by: Michael Devine. 8884009669


PROGRAMMING WITH PYTHON 3.X.x – ITERATION & RANGE

Any sequence works in a for, as it’s a generic tool. For example, for loops work on strings
and tuples:

>>> S = "lumberjack"
>>> for x in S:
print(x, end=' ')
lumberjack
>>>
>>> T = ("and", "I'm", "okay")
>>> for x in T:
print(x, end=' ') # Iterate over a tuple

and I'm okay

>>> words = ['apple', 'mango', 'banana', 'orange']


>>> for w in words:
print( w, len(w))

apple 5
mango 5
banana 6
orange 6

>>> words = ['this', 'is', 'an', 'ex', 'parrot']


>>> for word in words:
print( word)

this
is
an
ex
parrot

>>> numbers=(0,1,2,3,4,5,6,7,8,9)>>>
>>> for number in numbers:
print( number, end=' ')

0123456789
>>>

Compiled by: Michael Devine. 8884009669


PROGRAMMING WITH PYTHON 3.X.x – ITERATION & RANGE

USING ELSE WHILE REPEATING

> > > for food in (“pate”, “cheese”, “crackers”, “yogurt”):


if food == “yogurt”:
break
else:
print(“There is yogurt!”)

> > > for food in (“pate”, “cheese”, “crackers”):


if food == “yogurt”:
break
else:
print(“There is no yogurt!”)

There is no yogurt!

In each example, there is a test to determine whether there is any yogurt. If there is, the
while ... : is terminated by using a break . However, in the second loop, there is no yogurt
in the list, so when the loop terminates after reaching the end of the list, the else: condition
is invoked.

There is one other commonly used feature for loops: the continue statement. When
continue is
used, you’re telling Python that you do not want the loop to be terminated, but that you
want to skip the rest of the current statements of the loop and go back to the top, re -
evaluate the conditions and the list for the next round.

USING CONTINUE TO KEEP REPEATING

> > > for food in (“pate”, “cheese”, “rotten apples”, “crackers”, “whip cream”, “tomato
soup”):
if food[0:6] == “rotten”:
continue
print(“Hey you can eat %s” % food)

Hey, you can eat pate


Hey, you can eat cheese
Hey, you can eat crackers
Hey, you can eat whip cream
Hey, you can eat tomato soup

Because you’ve used an if ... : test to determine whether the first part of each item in the
food list contains the string “ rotten ” , the “ rotten apples ” element will be skipped by the
continue , whereas everything else is printed as safe to eat.
Compiled by: Michael Devine. 8884009669
PROGRAMMING WITH PYTHON 3.X.x – ITERATION & RANGE

NESTED LOOPS
Python programming language allows to use nested loops i.e., one loop inside
another loop.

for x in range(1, 11):


for y in range(1, 11):
print( '%d * %d = %d' % (x, y, x*y))

The output of the above program would looks like the below partial output.
1*1=1
1*2=2
1*3=3
1*4=4
1*5=5
1*6=6
1*7=7
1*8=8
1*9=9
1 * 10 = 10
2*1=2

and so on up to

10 * 10 = 100

Compiled by: Michael Devine. 8884009669


PROGRAMMING WITH PYTHON 3.X.x – ITERATION & RANGE

Find prime number within 30 integer numbers from 1 – 30

#find prime number within 30 integer numbers from 1 - 30


i=1
while(i <= 30):
j=2
while(j <= (i/j)):
if not(i%j):
break
j=j+1
if (j > i/j) :
print(i, " is prime")
i=i+1
print( "Good work!")

The output of the above program is as follows:

5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
Good work!

The next example illustrates statement nesting and the loop else clause in a for. Given a
list of objects (items) and a list of keys (tests), this code searches for each key in the objects
list and reports on the search’s outcome:

>>> items = ["aaa", 111, (4, 5), 2.01] # A set of objects


>>> tests = [(4, 5), 3.14] # Keys to search for
>>>
>>> for key in tests: # For all keys
for item in items: # For all items
if item == key: # Check for match
print(key, "was found")
break
else:
print(key, "not found!")

(4, 5) was found


3.14 not found!
Compiled by: Michael Devine. 8884009669
PROGRAMMING WITH PYTHON 3.X.x – ITERATION & RANGE

Because the nested if runs a break when a match is found, the loop else clause can assume
that if it is reached, the search has failed.

Notice the nesting here. When this code runs, there are two loops going at the same time:
the outer loop scans the keys list, and the inner loop scans the items list for each key. The
nesting of the loop else clause is critical; it’s indented to the same level as the header line of
the inner for loop, so it’s associated with the inner loop, not the if or the outer for. This
example is illustrative, but it may be easier to code if we employ the in operator to test
membership. Because in implicitly scans an object looking for a match (at least logically),
it replaces the inner loop:

>>> for key in tests: # For all keys


if key in items: # Let Python check for a match
print(key, "was found")
else:
print(key, "not found!")

(4, 5) was found


3.14 not found!
>>>

The next example is similar, but builds a list as it goes for later use instead of printing. It
performs a typical data-structure task with a for — collecting common items in two
sequences (strings)—and serves as a rough set intersection routine. After the loop runs, res
refers to a list that contains all the items found in seq1 and seq2:

>>> seq1 = "spam"


>>> seq2 = "scam"
>>> res = []
>>> for x in seq1: # Scan first sequence
if x in seq2: # Common item?
res.append(x)
>>> res
['s', 'a', 'm']
>>>

Compiled by: Michael Devine. 8884009669


PROGRAMMING WITH PYTHON 3.X.x – ITERATION & RANGE

THE RANGE() BUILT-IN FUNCTION


The value we put in the range function determines how many times we will loop.
The way range works is it produces a list of numbers from zero to the value minus one.
For instance, range(5) produces five values: 0, 1, 2, 3, and 4.

If you do need to iterate over a sequence of numbers, the built-in function range() comes in
handy. It generates lists containing arithmetic progressions:

>>> range(10)
range(0, 10)
>>> range(0, 10)
range(0, 10)
>>> range(5,10)
range(5, 10)
>>> print(range(10))
range(0, 10)
>>> list(range(0, 10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> str(range(10))
'range(0, 10)'
>>> tuple(range(10))
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

The Starting, Stopping, and Stepping Arguments to range()


Ranges work like slices. They include the first limit (in this case), but not the last (in
this case). Quite often, you want the ranges to start at 0, and this is actually assumed if you
only supply one limit (which will then be the last):

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

If we want the list of values to start at a value other than 0, we can do that by specifying the
starting value. The statement range(1,5) will produce the list 1, 2, 3, 4.

Another thing we can do is to get the list of values to go up by more than one at a time. To
do this, we can specify an optional step as the third argument. The statement range(1,10,2)
will step through the list by twos, producing 1, 3, 5, 7, 9.

Compiled by: Michael Devine. 8884009669


PROGRAMMING WITH PYTHON 3.X.x – ITERATION & RANGE

To get the list of values to go backwards, we can use a step of -1. For instance, range(5,1,-
1) will produce the values 5, 4, 3, 2, in that order.

>>> range(-10, -100, -30)


range(-10, -100, -30)

USING THE RANGE FUNCTION WITH LOOPS.


The while loop keeps looping while its condition is True (which is the reason for its
name), but what if you want to execute a block of code only a certain number of times? You
can do this with a for loop statement and the range() function. In code, a for statement
looks something like for i in range(5):

>>>
>>> for i in range(5):
pass
>>> i
4
>>>

This lets you change the integer passed to range() to follow any sequence of integers,
including starting at a number other than zero.

>>>
>>> for i in range(12, 16):
print(i)
12
13
14
15
>>>

The first argument will be where the for loop’s variable starts, and the second argument
will be up to, but not including, the number to stop at.

Compiled by: Michael Devine. 8884009669


PROGRAMMING WITH PYTHON 3.X.x – ITERATION & RANGE

The range() function can also be called with three arguments. The first two arguments
will be the start and stop values, and the third will be the step argument. The step is the
amount that the variable is increased by after each iteration. So calling range(0, 10, 2)
will count from zero to eight by intervals of two.

>>>
>>> for i in range(0, 10, 2):
print(i)
0
2
4
6
8
>>>

The range() function is flexible in the sequence of numbers it produces for for loops. For
example you can even use a negative number for the step argument to make the for loop
count down instead of up.

>>>
>>> for i in range(5, -1, -1):
print(i)
5
4
3
2
1
0
>>>
>>>

Compiled by: Michael Devine. 8884009669


PROGRAMMING WITH PYTHON 3.X.x – ITERATION & RANGE

EXERCISES:

>>>
>>> for number in range(1,101):
print( number, end=',')
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,
34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,6
3,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92
,93,94,95,96,97,98,99,100,
>>>

>>> sum=0
>>> for n in range(0,100):
sum+=n
>>> sum
4950
>>>

>>>
>>> for i in range(4):
print('*'*(i+1))
*
**
***
****
>>>

>>>
>>> for row in range(8):
for col in range(6):
print('*', end='')
print()
******
******
******
******
******
******
******
******
>>>
>>>

Compiled by: Michael Devine. 8884009669


PROGRAMMING WITH PYTHON 3.X.x – ITERATION & RANGE

>>>
>>> rows = int(input('How many rows? '))
How many rows? 3
>>> cols = int(input('How many columns? '))
How many columns? 4
>>> for r in range(rows):
for c in range(cols):
print('*', end='')
print()
****
****
****
>>>
>>> num_steps = 6
>>> for r in range(num_steps):
for c in range(r):
print(' ', end='')
print('#')
#
#
#
#
#
#
>>>
>>> for x in range(-10, -100, -30):
print("We're in %d position" % (x))
We're in -10 position
We're in -40 position
We're in -70 position
>>>
>>> for x in range(0, 3):
print("We're in %d position" % (x))
We're in 0 position
We're in 1 position
We're in 2 position
>>>
>>>

Compiled by: Michael Devine. 8884009669


PROGRAMMING WITH PYTHON 3.X.x – ITERATION & RANGE

To iterate over the indices of a sequence, you can combine range() and len() as follows:

>>>
>>>a = ['Mary', 'had', 'a', 'little', 'lamb']
>>>
>>>for i in range(len(a)):
print( i, a[i])
0 Mary
1 had
2a
3 little
4 lamb

Sometimes you want to iterate over two sequences at the same time. Let’s say that you have
the following two lists:

>>>
>>> names = ['anne', 'beth', 'george', 'damon']
>>> ages = [12, 45, 32, 102]
>>>
>>> for i in range(len(names)):
print( names[i], 'is', ages[i], 'years old')
anne is 12 years old
beth is 45 years old
george is 32 years old
damon is 102 years old
>>>
>>>

Compiled by: Michael Devine. 8884009669

You might also like