0Yh8EJO0RHMdx8oqkyOId

Python Basics Lesson 2: Loops

article featured image

Loops can execute a block of code number of times until a certain condition is met. In Python we commonly use the WHILE loop and the FOR loop.

A WHILE Loop is used to repeat a block of code. Instead of running the code block once, It executes the code block multiple times until a certain condition is met. A WHILE loop is written like this:

while :

Let’s look at an example. Let’s say we want to print numbers from 0 to 5. We can write this using a WHILE loop as such:

x = 0 while (x < 6): print(x) x = x + 1

As we can see here, on the first execution of this loop we will check to see if (x < 6) evaluates to TRUE. If it does, as it does in this example it will print x to the console and then add 1 to x. Once this happens it will repeat the check to see again if (x < 6). It will do this until this expression evaluates to FALSE. The output of this will be:

0 1 2 3 4 5

A FOR loop is used to iterate over elements of a sequence. It is often used when you have a piece of code which you want to repeat "n" number of times. A FOR loop is written like this:

for :

Using the same example as the WHILE loop, let’s print numbers from 0 to 5. We can write this using a FOR loop as such:

for x in range(0,6): print(x)

In this example we now specify the range of numbers we want x to be and we do not need to add 1 to x on each repeat as that is done for us. You can similarly use a FOR loop to iterate over different data types and not just numbers. For example in later lessons you will learn about lists, dictionaries, collections, etc.

Tags:

Comments

Leave a comment