Loops in Python

Updated 13 April 2022

To better yourself for future programming skylarking let me welcome you to the next step of understanding Python. Loops are among the most basic yet also the most powerful features in programming. Utilised by all modern programming languages loops effectively instruct a computer to repeat a process until a specified condition is reached. This specified condition can be thought of as a question to the computer. The same question is asked again and again until the criteria are fulfilled and no further looping action is necessary. Each time the question is asked it is called an iteration. Iteration is a general term for taking each item of something, one after another. The need for defining the loop in a software program can arise for many, many reasons depending on the task performed by the computing task.  Loops are wonderfully helpful, allowing the flow of code to become circular and iteration to transpire. Without them, it would often take lines and lines of code to enact similar results.

So, this guide is to stop Python from throwing you for a loop! It will present an overview of all the loop types within Python. Also, nested loops will be investigated. nested loop is a loop within a loop, ergo, an inner loop within the body of an outer one. Furthermore, control structures will be re-established and utilised. Control structure flowcharts are an excellent method of grasping the movement that the computing device reads code, more information can be found at the guide Control Structures with Python

Clossssssssing the loooopsssss

The contents of this guide can be seen below. 

There are several related tutorials on our website to help you become a coding wizard. A great place to start would be Python Rundown and Main Windows and Python and MicroPython - Compare and Access. These will also tell you where to download Python and access online Python emulators. Python is an excellent language to utilise with Raspberry Pi Boards such as Raspberry Pi 4 Model B 8GB. These are computing devices that can easily fit on the palm of your hand.

There is always more than one way to solve a programming problem and this is where personal flair and coding style flourishes. As always if you have any questions, queries or things to add please let us know your thoughts!


Overview of All Loops in Python
Snake taken for a loop

Loops, in general, are used to traverse through data or a process sequentially. Loops usually have a definite iteration amount. This means the number of repetitions is specified explicitly in advance. The opposite of this is infinite loops. This is code that will essentially repeat forever. This is because the code either has no terminating condition, the exit condition is never met, or the loop is instructed to start over from the beginning. It is possible to effectively use infinite loops. For example, they can be used in a game for drawing to update the game state or they can be used in devices that try to keep WIFI network connections active. 

It is also worth noting any type of loop can be put inside any other loops any amount of times. This is referred to as loop nesting or a nested loop.

There are two distinct types of loops in Python, for statements and while statements. It is worth noting both loops can be used interchangeably for any situation, they just require altered syntax or approaching the programming conundrum in a different way.

- For LoopIn Python, they are started by using the | for | keyword. This is a looping structure that runs a sequence of statements multiple times for a pre-set number of times. The sequence of statements that are repeated is referred to as the loop body. This means they are explicitly bounded iteration methods. Once the fixed number of loops are completed the code will move onto the next stage. Typically, for loops will run through each element in a list using the index number as the iteration method.

- While Loop. In Python, they are started by using the | while | keyword. This is a looping structure that is repeated if a conditional expression is true. It will test this each time before executing the loop body. Conditional expressions are features of a programming language that performs different actions depending on whether a specified boolean condition evaluates to true or false. While loop is used in situations where we do not know how many times the loop needs to be executed beforehand. Often unbounded iteration which means it will continue to loop until some condition is met.


Control Structures

Control structures are a flowchart method to represent the control flow of programming languages. In computer science, the control flow is the order in which individual statements, function utilisation or instructions of a software program are executed. This is also referred to as the flow of control. Simply program flow is a general term which describes the order in which your lines of code are evaluated by the computing device.

Control structure flowcharts convey each step in the software program as boxes of various kinds. The order is demonstrated by connecting the boxes with arrows. The shape of the box represents the code line type and allow for easier identification. The shape of the box can represent either a command statement, a variable creation, a condition or a decision. A great reference point for these can be found at Control Structures in Python.


For Loop

A simple example of a for loop structure can be seen in the script below which has been written in the Python Programming Window. The results of this script can also be seen in a Python IDLE Shell adjacent. Further below is a control structure flowchart representing this script. The flowchart demonstrates exactly the path of execution that the computer does when this script is run. This script adds up all the values inside a list variable. It uses the keyword in | to allow each element inside the list to be evaluated one by one. This results in an iteration.

Syntax worth noting, when you finish the line which initialises the loop you must end the statement with | : |. Furthermore, all parts of the script which are part of the loop body must have an indentation. This is achieved either by entering four spaces with the spacebar key or a single press of the tab key, both found on your keyboard. 

For Loop occurring in Python code to count up all the integers in the list

Control Structure Flowchart Annotated with code that performs a for loop 


While Loop

A simple example of a while loop structure can be seen in the script below which has been written in the Python Programming Window. The results of this script can also be seen in a Python IDLE Shell adjacent. Further below is a control structure flowchart representing this script. The flowchart demonstrates exactly the path of execution that the computer does when this script is run. This script adds up all the values inside a list variable. It uses the keyword | len | to figure out how many iterations should occur. This keyword, when given the identifier of a list variable, gives back an integer value for how many elements are inside the list. 

Syntax worth noting, when you finish the line which initialises the loop you must end the statement with | : |. Furthermore, all parts of the script which are part of the loop body must have an indentation. This is achieved either by entering four spaces with the spacebar key or a single press of the tab key, both found on your keyboard. 

While Loop occurring in Python code to count up all the integers in the list

Control Structure Flowchart Annotated with code that performs a while loop


Nested Loops

Python programming language allows you to use loops inside another loop. This is referred to as a nested loop. The nested loop can use different loop types or the same types and run perfectly fine. Below is a script that has been written in the Python Programming Window where a while loop has been nested inside another while loop. The results of this script can be seen in a Python IDLE Shell adjacent. This script counts down two variable values and prints a nice looking pyramidical result.

Loops within loops open up new dimensions of possibilities and this example demonstrates this whilst remaining simplistic and hopefully easy to understand. Further below is the control structure flowchart for this script. This demonstrates how the nested loop structure operates and also aid understanding of what exactly the flow of code execution is to produce this interesting pyramidical print result to the Python IDLE Shell.

Nested loop example. This demonstrates two while loops one running inside the other.

The control structure for a nested looping structure with two while loops. One inside the other one.


The Next Step

After seeing how to run loops within loops the natural next step would be to learn how to use | break |, | pass | and | continue | keywords effectively within looping structures. You can find the next step here in Pass, Break and Continue Keywords within Python.

After this future tutorials will focus on the | if |, | elif |, and | else | keywords in union with looping structures. The skills to utilise them by themselves and in conjunction with looping structures will become invaluable in your coding adventures. You can also use the keywords | for | and | else | to create the lesser known for/else statement which makes for a very powerful tool.


Download the Codes

Below you can find all the code for the above examples. You will be able to run the codes here on your own computing device and modify the code at your leisure. Open it up with Python IDLE Shell and run it using the Python Programming Window.  

Attachment - Python-Looping-Codes.zip

Have a question? Ask the Author of this guide today!

Please enter minimum 20 characters

Your comment will be posted (automatically) on our Support Forum which is publicly accessible. Don't enter private information, such as your phone number.

Expect a quick reply during business hours, many of us check-in over the weekend as well.

Comments


Loading...
Feedback

Please continue if you would like to leave feedback for any of these topics:

  • Website features/issues
  • Content errors/improvements
  • Missing products/categories
  • Product assignments to categories
  • Search results relevance

For all other inquiries (orders status, stock levels, etc), please contact our support team for quick assistance.

Note: click continue and a draft email will be opened to edit. If you don't have an email client on your device, then send a message via the chat icon on the bottom left of our website.

Makers love reviews as much as you do, please follow this link to review the products you have purchased.