Loops and functions

Loops and functions

A teacher has marks for 5 subjects and 40 students, so must the same code be typed 200 times? See how lists, loops and functions let you write it once.

A teacher going down an attendance register, marking each student present or absent

Taking attendance

A teacher takes attendance. She has no separate plan for each student. She repeats one step, “call the name, mark present or absent”, down the register.

Programs repeat work the same way. First we need the register: many values kept in one place.

Lists

Riya has marks in 5 subjects. Instead of 5 variables, we keep them in one “list”, written in square brackets:

marks = [72, 85, 90, 64, 78]
print(marks[0])
print(len(marks))
Output
72
5

Each value has a position, and Python counts positions from 0. So marks[0] is the first value.

The for loop

Now the repeating step. for takes each value from the list in turn and runs the indented block for it:

marks = [72, 85, 90, 64, 78]
for m in marks:
    print(m)
Output
72
85
90
64
78

m holds the current value. Code that repeats like this is called a “loop”.

A running total

To find Riya’s average, we add the marks one by one, like on a calculator:

marks = [72, 85, 90, 64, 78]
total = 0
for m in marks:
    total = total + m
print(total / len(marks))
Output
77.8

total starts at 0 and grows on every round: 72, 157, 247, 311, 389. Then 389 ÷ 5 gives 77.8.

Loop plus condition

Loops and conditions work together. In how many subjects did Riya score above 75?

marks = [72, 85, 90, 64, 78]
count = 0
for m in marks:
    if m > 75:
        count = count + 1
print(count)
Output
3

The if from the last lesson sits inside the loop, indented one more level. It runs once for every mark.

The while loop

Sometimes we don’t know the number of rounds in advance. Riya saves ₹2,000 a month for a ₹9,000 tablet. while repeats as long as its condition is True:

saved = 0
months = 0
while saved < 9000:
    saved = saved + 2000
    months = months + 1
print(months)
Output
5

After 5 months she has ₹10,000, and the loop stops.

One block of instructions copied into identical pages for several students

The same work again

Riya’s average took 5 lines. Her class has 40 students. Should we copy those 5 lines 40 times?

If the school changes the formula, we must fix 40 copies and will surely miss one. We need to write the steps once and reuse them.

An ATM taking in an amount on one side and handing out cash on the other

A machine with a button

Think of an ATM. You give it an amount, it does several steps inside and hands you cash. It works the same for every customer.

In programming, such a reusable machine is called a “function”. In fact, print and len are functions someone already wrote.

Defining a function

We build our own with def. Let’s wrap the average steps:

def average(marks):
    total = 0
    for m in marks:
        total = total + m
    return total / len(marks)

marks in the brackets is the input, called a “parameter”. return hands back the result. Nothing prints yet. We have only built the machine.

Calling a function

To use the machine, write its name with real values in the brackets. This is “calling” the function.

riya = [72, 85, 90, 64, 78]
arjun = [55, 61, 70, 48, 66]
print(average(riya))
print(average(arjun))
Output
77.8
60.0

One definition, used twice. It would work for all 40 students.

Return values

The value a function returns can be stored and used like any other value:

avg = average(riya)
if avg >= 75:
    print("Distinction")
else:
    print("Pass")
Output
Distinction

The function calculates and the if decides. Small pieces, each with one job, combine into bigger programs.

Summary

  1. List: Many values in one variable, in square brackets. Positions start at 0.
  2. Loops: for repeats a block for each value in a list. while repeats while a condition is True.
  3. Function: Reusable steps with a name, built with def and run by calling it.
  4. Inputs and outputs: Parameters carry values in. return hands the result back.