Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

Introduction to Python Loops

Hugh Donnelly
Python in Plain English
7 min readApr 24, 2021

--

Instruction, media content, examples and links to resources that will help you build a foundation for Python competency. Jupyter Notebooks are available on Google Colab and Github.

Web Resources
Docs.python.org — Control Flow
Docs.python.org — Looping Techniques

What are Python Loops?

In the real world, you often need to repeat something over and over. It can be repetitive. When programming, though, if you need to do something 100 times, you certainly don’t need to write it out in 100 identical lines of code. In Python, loops allow you to iterate over a sequence, whether that’s a list, tuple, string, or dictionary.

What types of Python Loops are there?

There is a for loop and a while loop. We’ll also go through list comprehensions, as a “Pythonic” powerful shortcut for operating on all the members of a list in a single line of code.

The for statement

A “for” loop in Python allows you to go through each item in a sequence, one at a time. This allows you to “iterate” through an “iterable”, such as a Python list, and perform operations on each item one at a time.

The simplest example is to step through the items in a list:

# In the below example, the for loop will step through each item
# in my_list, assign the element to a local variable ("x"),
# and execute the block of code below it to print out x.
my_list = [10, 20, 30, 40, 50, 60]# x is a variable, who's scope is limited to the for loop. x can be named anything you'd like.for x in my_list:
print(x)

The range() function

In most cases, we will want to loop through a predetermined list. However, we can also generate a list to loop over “on the fly” with the range() function.

for i in range(8):
print(i)

--

--

Published in Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.

Written by Hugh Donnelly

Hugh founded AlphaWave Data in 2020 and is responsible for risk, attribution, portfolio construction, and investment solutions.

No responses yet

Write a response