In programming we are often doing the same set of instructions repeatedly to tackle this we can use two different types of loops:
If we wanted to write a program that counts from 1 to 10 we could make the program like this:
i = 0 print(i+1)print(i+2)print(i+3)print(i+4)...
As you can see we are repeating the print statement which is inefficient. To simplify this we can write the program like this:
for i in range(10): print(i+1)
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 = 0for i in 5, 7, 11, 13: print(i) total = total + iprint(total)
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 = 0for number in 5, 7, 11, 13: print(i) 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
for VARIABLE in CONDITION: DO STATEMENT
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