Python training exercise 5

From BITS wiki
Jump to: navigation, search

Introduction

Another important feature of computer programs is that they can do the same thing over and over again with different information. To allow this, it is possible to use loops in the program; essentially a loop is executed until it runs out of data or the code decides to break out of it.

Exercises

for loops

Now that we have these variables that can hold multiple elements (previous exercise), it would be useful to be able to loop over them one by one. This is possible with the for loop:

myList = range(10)
 
for myElement in myList:
  print("Counting {}".format(myElement))

Note that again we have to use indentation, as there is a block of code that is only relevant within the for loop.

The for loop works exactly the same with tuples:

myTuple = ("A","B","C","D","E","F")
 
for myElement in myTuple:
  print("Letter {}".format(myElement))

Because you can access individual elements within a list or tuple, you can also count the element index in the list or tuple, so that you know both index and value.

myTuple = ("A","B","C","D","E","F")
myTupleLength = len(myTuple)
 
for tupleIndex in range(myTupleLength):
  myElement = myTuple[tupleIndex]
  print("Letter {} is at position {}".format(myElement,tupleIndex + 1))  # We have to add 1 to the index here because Python starts at zero...

If we now return to the example where we want to find out if a number is divisible by another, it becomes much easier to test a large set of values:

myNumbers = range(1,501)
myDivider = 17
 
for myNumber in myNumbers:
  if not (myNumber % myDivider):  # Nothing left after division, so number is divisible.
    print("Number {} can be divided by {}!".format(myNumber,myDivider))

Here we now have two levels of code besides the main one; the if is checked for every value, but the print is only executed for numbers divisible by myDivider.

You can also control the loop by using continue and break. It is best to use these sparingly however as they interrupt the 'flow' of the code:

myNumbers = range(1,10)
 
for myNumber in myNumbers:
 
  if myNumber == 5:   
    continue          # This means the rest of the for: code will be ignored, we 'jump back' to the start and use the next number (6)
 
  print(myNumber)
 
  if myNumber == 8:
    break             # This means we will exit the loop alltogether, all other values after this one will not be dealt with.

while loop

A while loop is dependent on a condition, as long as this condition is evaluated as True the loop will continue. This is an endless loop:

while True:
  print("Endless...")

If you execute this, press CTRL-C to break the program.

While loops are more flexible than for loops, as you can make them end whenever necessary depending on code within the loop itself:

baseValue = 2
powerValue = 1
powerResult = 0
while powerResult < 1000:
  powerResult = baseValue ** powerValue
  print("{} to the power {} is {}".format(baseValue,powerValue,powerResult))
  powerValue += 1 # Add one to itself - this kind of step is crucial in a while loop, or it will be endless!

Note that the last value printed is greater than 1000, the while condition is only checked at the start of the loop. You can avoid this by initialising the loop and putting the calculation at the very end:

baseValue = 2
powerValue = 1
powerResult = 0
powerResult = baseValue ** powerValue
 
while powerResult < 1000:
  print("{} to the power {} is {}".format(baseValue,powerValue,powerResult))
  powerValue += 1 # Add one to itself - this kind of step is crucial in a while loop, or it will be endless!
  powerResult = baseValue ** powerValue



Back to main page