for Loops
The for loop in Python is used to iterate over a sequence (list, tuple, string, dictionary) or other iterable objects. Most useful when the number of times to execute the body is definite.
Syntax of the for Loop:
>>> for item in sequence:
>>> Body of loop
Here item is the variable that takes the value of the item inside sequence. The code in the body of the loop gets executed for item. The loop continues until we reach the last item in sequence. The body of the loop is separated from the rest of the code using indentation.
Flowchart of a for Loop:
Example:
>>> # code to find the sum
>>> # of all numbers stored in a list
>>>
>>> numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] #list of numbers
>>>
>>> sum = 0 #variable to store the sum
>>>
>>> for val in numbers: #iterate over the list
>>> sum = sum + val
>>>
>>> print "The sum is", sum
The sum is 48
Assignment operators (revisited):
**note the special notation for performing operations on an existing value
Example:
>>> # code to find the sum
>>> # of all numbers stored in a list
>>>
>>> numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] #list of numbers
>>>
>>> sum = 0 #variable to store the sum
>>>
>>> for val in numbers: #iterate over the list
>>> sum += val #add val to sum and store as sum
>>>
>>> print "The sum is", sum
The sum is 48
The range() function
A sequence of numbers can be generated using the range() function. range(x) returns a list of numbers from 0 (default) up to, but not including, x.
Example:
>>> print range(5)
[0, 1, 2, 3, 4]
We can also define the start, stop, and step as range(start, stop, step). Step defaults to 1 if not included.
Example:
>>> print range(2, 8)
[2, 3, 4, 5, 6, 7]
Example:
>>> print range(2, 20, 3)
[2, 5, 8, 11, 14, 17]
We can use range() to iterate through a sequence of numbers. It can be combined with len() to iterate through a sequence using indexing.
Example:
>>> genre = ['blues', 'rock', 'jazz'] #list of music genres
>>>
>>> for i in range(len(genres)): #iterate over list using index
>>> print ('I like', genre[i])
I like blues
I like rock
I like jazz
for Loop with conditional:
A for loop can have an optional if-else block as well. A break statement can be used to stop a for loop. In such cases the block of code that follows is ignored.
Example:
>>> list_of_digits = [0, 1, 2, 3, 4, 5, 6]
>>>
>>> input_digit = 3
>>>
>>> #compare the equality of the input
>>> #digit with each element of the list
>>> for i in list_of_digits:
>>> if input_digit == i:
>>> print 'Digit is in the list.'
>>> break #if the values are equal, end the loop
>>> else:
>>> print 'Digit not found in list.'
Digit not found in the list.
Digit not found in the list.
Digit not found in the list.
Digit is in the list.
Here we have a list of digits from 0 to 6. There is an input value (hardwired in the code now but easily replaced with input() later when the code is functional) to be checked as to whether it exists in the list or not. If at any point the digit is found the for loop breaks prematurely.
Nested for loops:
The for loop controls a statement, and the for loop is itself a statement, which means that one for loop can control another for loop. For example, you can write code like the following:
>>> for i in range(6):
>>> for j in range(1,4):
>>> print j,
1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
If read from inside out, the inner loop prints the value of its control variable j as it varies from 1 to 3. The outer loop executes this six different times. As a result we get six occurrences of the sequence 1 2 3 as output. This output all occurs on the same line because of the comma at the end of the print statement, else there would have been 18 lines of output with one number on each.
When you write code that involves nested loops, you have to be careful to indent the code correctly to make the structure clear.
Example:
>>> for i in range(6):
>>> for j in range(10): #prints 10 *'s on one line
>>> print '*',
>>> print '' #creates the next line
**********
**********
**********
**********
**********
**********
Example:
>>> for i in range(1, 7):
>>> for j in range(1, i+1): #the number of *'s is based
>>> print '*', #on the current value of i
>>> print ''
*
* *
* * *
* * * *
* * * * *
* * * * * *