Introduction to Loops

Updated on 28 Dec 2022

Python offers you 2 types of loops.

  • while loops
  • for loops

while loops

These are loops that will continue to run until a condition is met. Usually you would use this loop when you don’t know how many iterations you need. Typcially examples might be reading lines from a text file, or waiting for some other condition to be met. I.e. read all the words until you find one with a value of brent.

In the example below, we have a counter that increments by one, and the loop continues to execute until the counter reaches the value defined by maxline.

maxline = 5
counter = 0
process = True

while process:
    counter = counter + 1
    print('Hello line {0}'.format(counter))

    if counter == maxline:
        process = False

Another way of writing the above code is to put the conditional as part of the while loop.

while counter < maxline:
    counter = counter + 1
    print('Hello line {0}'.format(counter))

Notice in this example we don’t have to worry about setting the process variable, and some might argue that the second example is more succint.

blah blah

= is assignment where you assign a value to a variable. == is equilavency where you check if the 2 values are the same. I.e. in the example code we are checking if the value of counter is the same as the value for maxline

for loops

for loops are used to iterate over a sequence. There are different types of sequences, but for these examples we’ll focus on the simple list.

mylist = ['brent', 'sooty', '14']

Just like the earlier examples with variables, we can print the list, print(mylist).

But we can also loop over the contents.

for v in mylist:
    print('item: {item}'.format(item=v))

In this case, each iteration will put the element into the variable v which we can then use. In this case we are just printing it.

We can also do stuff with the elements inside the loop.

mylist = ['brent', 'sooty', '14']

for v in mylist:

    if v == 'sooty':
        v = v.capitalize()

    print('item: {item}'.format(item=v))

Notice in the output that sooty now has a capital S.

Loops - guided exercise

Given the following list

mylist = ['brent', 'sooty', '14']

Write the code that will give the output shown below.

Solution

We may not have all the details for a solution in place yet, so let’s start with what we do know.

words   = 0 # number of words in the list
numbers = 0 # number of 'numbers' in the list
mylist  = ['brent', 'sooty', '14']

for v in mylist:
    pass
    #do some stuff

print('there are {0} words and {1} numbers'.format(words, numbers))

Note: Loops and conditionals are expecting code inside them. If you are just filling out a stub and need to come back to it later, then you can use the pass keyword that will ensure you don’t get any errors when you try to run your script.

Okay so we are on the right track and we just have to figure out how to increment words and numbers. If we go back to the variables exerise we will find a technique to get the str (short for string) documentation. If you want to cheat, use this link instead.

If we scroll down we’ll find some interesting string functions.

  • isalnum
  • isalpha
  • isascii
  • isdecimal
  • isdigit
  • isnumeric

Some of these will be useful for us, so lets update our loop and see what happens.

for v in mylist:
    if v.isalpha():
        words = words + 1
    if v.isdigit():
        numbers = numbers + 1

We get the output that we are expecting to see.