You are on page 1of 3

Lesson 16 For loop and range()

function
Assignment 4
Q2 Speech analysis
-

Lookup function set() it will make life easier, super powerful

The For statement


The For statement is a convenient way to Iterate over Sequences
for statement
for k in sequence:

Example use
nums = [10, 20, 30, 40, 50, 60, 70]

suite
for k in nums:
print(k)

Variable k is referred to as a loop variable.


With six elements

Why is it better than while loop?


Printing numbers in a sequence nums, using while loop
K=0
While k < len(nums):
Print nums(k)
K=k+1
In the while loop version, loop variable k must be initialized to 0 and incremented by
1 each time through the loop

In the for loop version loop variable k automatically iterates over the provided
sequence of values:
For k in nums:

Print(k)
Three things every loop must have
1) Starting point
2) Increment
3) Stopping condition

Lets compare For vs While loops


Requirement
Starting Point
Increment or step
Stopping condition

WHILE loop
Programmers defined
loop variable
Programmer defined
Condition

FOR loop
First element in sequence
1 element at a time
Number of elements in a
sequence

When not to use for loops


When you have to stop in the middle of the list
You cannot terminate the for loop in the middle whereas with a while loop you can
add a Boolean condition
When while loops rock!
-

Sometimes you iterate until you find something, not interested in all
elements
More interested in the condition

Range Function
Range( 0, 5 )
0,1,2,3,4 (Does not include the upper limit)
You can also define range() with one parameter
Range( 5 ) = range( 0, 5)

The built in range function


Range function generates a sequence of integers that a for loop can iterate over,
Sum = 0
For k in range(1, 11):
Sum = sum + k
The values in the generated sequence include the starting value, up to but not
including the ending value.
Range(1, 11) generates

1-10
Range() does not return a list
Actually range does not create a sequence of integers, it creates a generator
function able to produce each next item of the sequence. This saves memory,
especially for long lists.
Therefore, typing range(0,9) in the python shell does not produce a list as expected
it simples echoes out the call to range

You might also like