For and While Loops in Python


In programming we are often doing the same set of instructions repeatedly to tackle this we can use two different types of loops:

For loops in Python

If we wanted to write a program that counts from 1 to 10 we could make the program like this:

i = 0 

As you can see we are repeating the print statement which is inefficient. To simplify this we can write the program like this:

for in range(10):

Notice how we write only one line of code usingi, but it takes on 10 different values?

The range(n) function can be considered a shorthand for 0, 1, 2, …, n-1.

You can also loop over elements of your choice so you do not have to use the range function:


total = 0
for i in 5, 7, 11, 13:
    total = total + i



For this program ‘i’ starts with 5. It then prints 5 and adds that to the total which started with 0.

‘i’ then becomes 7, 7 is printed and added to the total

‘i’ then becomes 11, 11 is printed and added to the total

‘i’ then becomes 13, 13 is printed and added to the total

The loop is finished

The total is printed


You do have to use ‘i’, if you wanted to use another word for example ‘number’ instead of ‘i’ so that the program is:

total = 0
for number in 5, 7, 11, 13:
    total = total + i

This would still return the same output. Programmers like to use i as it stands for index 

The basic structure for a ‘for loop’ is



  • Variable can be anything 
  • Condition usually has function range
  • Words ‘for’ and ‘in’ must be lower case and must be used 
  • Colon(:) is after the condition 
  • Statement needs to be indented 
  • A for loop is used when we know how many times we want to the loop

While Loops in Python

What about if we do not know how many times we want to run the loop?

For these kinds of situations we can use a while loop. The while loop exists as a tool for repeated execution based on a condition. The code block will keep being executed until the given logical condition returns a False Boolean value.

Lets make a game where the user has to guess the number you are thinking of:

ans = 0 while ans != 10:
    ans = int(input("Enter a number: "))
print("You win!")

This program will continuously ask the user to enter a number until the number 10 is inputted by the user