Skip main navigation

New offer! Get 30% off one whole year of Unlimited learning. Subscribe for just £249.99 £174.99. New subscribers only. T&Cs apply

Find out more

What are loops in coding?

Python provides the keywords and code structure, called loops, for repeating a code snippet. This will make your code more efficient.

There are scenarios, based on the evaluation of a condition, where we may need to repeat a block of code. Imagine you are a software developer and you are required to provide a software module for all the employees in your department, for example.

To do this, you must print the payroll details of each employee separately. Printing the details of all the employees will be a tiresome task, so instead, you can use the logic for calculating the details and keep on iterating the same logic statement.

For such practical purposes, Python provides the keywords and code structure, called loops, for repeating a code snippet. This will save you time and make your code more efficient.

Watch the video to learn about loops and how they work in Python.

What is ‘for loops’?

We use for loops in Python to loop over a collection (like list or tuple) or an iterator, and perform some action repetitively.

The standard syntax for a for loop is:

for value in collection:
 # do something with value

For example, in the code snippet, we are printing all the values stored in a list.

Code:

alist = [10,20,30,40,50,5,56,57]
for num in alist:
... print(num)
...

 

Output:
10
20
30
40
50
5
56
57

Loop control statements

There are various loop control statements that are used to break the usual repetition of code. Let’s look at code snippets of what these loop statements look like.

Break

A for loop can be exited altogether using the break keyword. In the following code, we are summing up the elements of the list until a None value is encountered, at which point the termination is executed.

Code:

sequence = [1,2,3,4,None,6,None,8,9,10]
total = 0
for value in sequence:
... if value == None:
... break
... total+=value
...
print(total)

 

Output:
10

Continue

In the following code we are summing up all the elements in the list, skipping the None values.

Code:

total = 0
for value in sequence:
... if value is None:
 continue
... total += value
...
print(total)

Output: 43

This article is from the free online

Data Analytics and Python Fundamentals

Created by
FutureLearn - Learning For Life

Reach your personal and professional goals

Unlock access to hundreds of expert online courses and degrees from top universities and educators to gain accredited qualifications and professional CV-building certificates.

Join over 18 million learners to launch, switch or build upon your career, all at your own pace, across a wide range of topic areas.

Start Learning now