Login
📚 Python for Introductory Statistics
Chapters ▾

4.1 The for Loop

Watch demo video

The for loop can be used to iterate over a sequence such as a list or other iterable objects.

Syntax:

 for i in sequence_name:      # i will take each value of sequence_name
    block statements

For Loop Flowchart

Flowchart of a for loop: each item taken from the sequence feeds the loop body, which repeats for the next item until no item is left, and the loop exits.

The flow of execution for a for statement:

  1. Take the first element in the list
  2. execute the block statement
  3. Go back to step 1
  4. Repeat step 1 to 3 until the last element of the list reached

Example: print the values of each element in the list x=[5, 10, 5, 4].

  1. Click + Code to add a code-cell
  2. Type x = [5, 10, 5, 4]
  3. Type for v in x:
  4. Type indented print(v)
x = [5, 10, 5, 4]
for v in x:  
	print(v)  
Show expected output
5
10
5
4

Note: When the program reaches the second line and encounters for, it uses v to store the first element in x. In the third line, it will print the current value of v. Then it will go back to the second line and use v to store the second element in x and prints this updated value of v. This pattern repeats till all elements in x are reached.

Watch demo video

Example: Given a list of integers, use the for loop to add all values in a list. Same as sum(x) from list operators.

x = [5, 10, 5, 4]
sum1 = 0            
for i in x:          
	sum1 = sum1 + i    
print("The sum is", sum1)
Show expected output
The sum is 24

Note: In the above code, i is the variable that takes the value of the elements inside the x list on each iteration. The for loop continues until the last element in the list is reached. The body of for loop is separated from the rest of the code using indentation.

Note: The flow of execution:

Begin

Enter for loop

Back to the for loop

Back to the for loop

Back to the for loop

Back to the for loop i=x[4] no element left in the list

Go to line 6

This could also be done using the sum(x) list operator as follows:

x = [5,10,5,4]
sum(x)
Show expected output
24

Example: Given a list of numbers, find its average. The average is the sum of all the numbers divided by size of the list.

x = [2.3,3.5,4,2.6,3.1,1.9]
sum1 = 0          
for i in x:  
  sum1 = sum1 + i
average = sum1/len(x)
print("the average is ", average)
Show expected output
the average is  2.9

Note: The total sum1 is the same as the code above. After the for loop in line 4, average=sum1/len(x). len(x) is the size or number of elements in x.

Example: The ages of current (as of 2020) US Senators are given below. Write a Python program that displays the number of Senators who are older than 65 years.

81,81,80,80,80,80,78,78,78,77,77,75,75,74,74,74,73,72,72,71,71,71,71,70,70, 70,70,68,68,68,68,68,67,67,67,66,66,65,65,65,65,64,64,64,64,64,64,63, 63, 63,63,62,62,62,62,62,61,61,61,60,60,59,59,59,59,59,59,59,59,58,58,57, 57,56,56,55,54,54,54,54,54,53,53,52,52,52,52,52,51,50,49,48,46,45,44,43,43, 43,42,41

age = [81,81,80,80,80,80,78,78,78,77,77,75,75,74,74,74,73,72,72,71,71,71,71,70,
    70,70,70,68,68,68,68,68,67,67,67,66,66,65,65,65,65,64,64,64,64,64,64,63,63,
        63,63,62,62,62,62,62,61,61,61,60,60,59,59,59,59,59,59,59,59,58,58,57,57,
        56,56,55,54,54,54,54,54,53,53,52,52,52,52,52,51,50,49,48,46,45,44,43,43,
        43,42,41]

count = 0
for i in age:
  if i > 65:
    count = count + 1
print(count)
print('Of the',len(age),'Senators,', count,'are over 65 years old')
Show expected output
37
Of the 100 Senators, 37 are over 65 years old

Note: age and count are defined first. In the for statement i takes the first element of age and checks if it is greater than 65. If true count = 0 + 1 if not true, it will go back to the for statement and i takes the second element in age. The pattern continues till the last element in age.

While Loop Flowchart

Flowchart of a while loop: a condition is tested; while it is true the loop body runs and control returns to the test, and when it is false the loop exits.

Syntax

while condition:
  block statements

The flow of execution for a while statement:

  1. Evaluate the condition, yielding True or False.
  2. If the condition is false, exit the while statement and continue execution at the next statement.
  3. If the condition is true, execute the body and then go back to step 1.

Example: Print the first 5 positive integers: 1, 2, 3, 4, and 5.

i = 0      
while i < 5:
   i = i + 1
   print(i)
Show expected output
1
2
3
4
5

Note: In the above code, the flow of execution is:

Begin in line 1

Enter while loop

Back to the while loop

Back to the while loop

Back to the while loop

Back to the while loop

Exit the loop

Example: Find the sum of the first 5 positive integers.

i = 0      
sum1 = 0
while i < 5:
   i = i + 1 
   sum1 = sum1 + i
   
print("Total sum:",sum1)
Show expected output
Total sum: 15

In the above code:

print sum = 15 (last value of sum)

Note: Fibonacci Numbers: 1,1,2,3,5,8,13,21,34,55,89,144,... The first two are 1 and 1. The rest are found by adding the two preceding numbers. The list can continue indefinitely.

Example: Write a Python program that lists a user given number of Fibonacci numbers.

# n = input("How many Fibonacci numbers do you want to list? ")
n = "10"   # ← web edition: the value the book's own run typed in

n = int(n)  # convert the default string to integer

i = 0   # initial counter
a = 1   # first number is 1
b = 1   # second number is 1

if n <= 0:
  print("Enter a positive integer")
if n == 1:
  print(a)
else:
 while i < n:   # repeat action while i < n is true
  print(a)     # print the first number
  i = i + 1    # increase i by 1 
  c = a + b    # add the previous two numbers and place it in c
  a = b        # update the last two numbers
  b = c        # update the last two numbers 
Show expected output
How many Fibonacci numbers do you want to list?10
1
1
2
3
5
8
13
21
34
55

Adapted from Python for Introductory Statistics, by Simon Aman (Truman College, City Colleges of Chicago), licensed under CC BY 4.0. Changes were made: reformatted as an accessible XYZ web edition with live in-browser code cells. License: CC-BY-4.0.