Python for beginners: Loops in Python

2018-07-09
Carton image to show loops as an introduction to python

A loop is describes the repetition of a certain command or a piece of code that needs to be executed over and over again.

Types of loops in Python:

Python, like other languages, has two main types of loops: the while loop and the for loop. A for loop is a control statement that iterates, or repeats, a piece of code a specific number of times. A while loop is a control statement that iterates a piece of code until a condition you specify becomes true.


There are several ways that can manipulate a loop. The break command stops a loop before the natural exit condition of the loop is met. If you want to continue the loop’s execution at the same place you broke, the continue command begins reading the code again wherever the loop stopped.

How long can it go?

The range command specifies the number of times you want to execute a for loop. For instance, if you want to loop over a statement four times, you can write:

For i in range(4):

By default, the range starts at 0 and increments by 1. The loop ends at the number you specified, so in the example of range(4) the loop will execute five times as the computer counts from 0 to 4.


You can start counting from a different number by adding the starting number in the brackets: range(2,6). You can also change the increment value by adding the value of the increment in the brackets: range(2,2,6). In this case, the loop will start at 2 and increase by 2 until it finishes at 6.

While loops:

While loops are similar to for loops except that the condition that specifies when the loop will end is included after the while keyword. For instance, if you want to have the loop continue to run while a variable called x is less than 3, you would write:

While x<3:

In this example, the loop will keep going until the value of the variable x reaches a value of 3 or greater. This will only occur if the value of x changes as the loop runs; otherwise, the loop will run forever.


Do you want to practice more and get familiar with this awesome language? You can build wonderful apps as you improve your programming skills. Start your learning journey with RoboGarden now. Register for free.


Python Series Introduction to Python

相关的博客

Start Python coding

Let's start python coding with RoboGarden learning journey.

Got an invite