Skip to main content
Enchanted Code

Python 3 iteration

tutorial, python

Intro

This tutorial will teach you about iteration, which is how you can repeat instructions in Python. In this tutorial I will be using lists, strings and integers to illustrate iteration.

Requirements

  • Know basics of Python 3 if not read here
  • Know about the lists data-structure, if not read here
  • Knowledge of iteration for computer science will help

What are they?

In Python you can create loops using the keywords “while” and “for”.

While Loop

Lets start with a while loop. To define a while loop you need the “while” keyword and a expression to check, this will be used to define whether to run the loop.

Infinite

Python allows us to create a loop that will always run we can do this using the code below.

while True:
    print("hello")

When run you will just see “hello” being outputted multiple times. This loop will never end.

Counter

Another way of running a while loop is to use a counter to determine when to “breakout” of the loop.

counter = 0
while counter != 5:
    print(counter)
    counter += 1

This loop will check whether the counter variable not is equal to 5, if it is the loop will “break”.

When run this code should output:

0
1
2
3
4

You can think of the expression in the while loop as a if statement and if the statement is true the loop will run; if not it will “break”.

For Loop

Another form of iteration found in Python is a for loop. this will use the “for” keyword.

Range

The first way of using a for loop is by using the range function. This allows for a start, stop and step value to be entered. This loop will also not require a separate counter variable.

As you can see in the code below the current value is being stored in the counter variable. The range function is also saying it will start from 0 and iterate until it reaches 5.

for counter in range(0, 5):
    print(counter)

When this code is run you should see:

0
1
2
3
4

This range function can also do some smart things. For example if you want to start from 0 you can omit the 0 and just have 5. This will mean it will start from 0 and iterate until 5.

As spoke about earlier can also define a step. Which you can see in the code below, the step is the last argument.

for counter in range(0, 10, 2):
    print(counter)

When run you should get the following output:

0
2
4
6
8

Iterable

The next way of using a for loop is to omit the range function and use a variable that has a iterable data-type like a list.

You can see this being used below:

my_list = ["hello", "world", "this", "is", "cool!"]

for item in my_list:
    print(item)

When run you should see the following output:

hello
world
this
is
cool!

A string is also counted as a iterable

Extras

Here are some extras that will work with both loops.

Break

The “break” keyword will stop the iteration of a loop. You can put this anywhere inside your loop.

for counter in range(5):
    print(counter)
    break

As you can see, the code will only output 0 and then stop.

0

Continue

The “continue” keyword allows for skipping to the start of the loop.

for counter in range(5):
    print(counter)
    continue
    print("hello")

As you can see this code will iterate through the range from 0 to 4. Because the “continue” keyword is placed before the print("hello"). It will instead go to do the next iteration of the loop.

When this code is run you should see the output shown below:

0
1
2
3
4

Both “break” and “continue” can be used in the same loop

Simple Calculator

We will now resume our simple calculator from the if statement tutorial.

We now want to allow unlimited values to be entered. Here is what you will need:

  1. Ask user what operation to use (+, -)
  2. Get number (store in list) (float)
  3. Ask whether another number is needed?
  4. If yes go to step 2 (while loop)
  5. Calculate the numbers using chosen operation
  6. Output the answer

Try to code your own version before looking at the completed code below.

numbers = []
answer = 0

operation = input("Operation (+ or -): ")

while True:
    number = input("Enter Number (leave blank to exit): ")
    if number == "":
        break
    number = float(number)
    numbers.append(number)

for curr_number in numbers:
    if operation == "+":
        answer += curr_number
    elif operation == "-":
        answer -= curr_number

print("Answer:", answer)

Lets test our application by adding 2 and 4. We should get an answer of 6.

Operation (+ or -): +
Enter Number (leave blank to exit): 2
Enter Number (leave blank to exit): 4
Enter Number (leave blank to exit):
Answer: 6.0

As you can see my code output indicates it works. If yours works well done. If it doesn’t have a look at mine and see where you went wrong.

Further Expansion

You should probably make sure that the calculator will work with more than 2 numbers.

If you have read my tutorial on functions, have a go and convert your code to use them. You could also add more operators like multiply and divide.

Research

Python has a lot of features, you should probably know about some more data-types like dictionaries and sets. Also learning about Python’s standard library will help you in future projects.