Python training exercise 5
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.
Write a program where you print out all positive numbers up to 1000 that can be divided by 13, or 17, or both. [click on show more for answer) |
---|
myNumbers = range(1,1001) myDividers = (13,17) # We will loop over these in the loop itself, so it's easy to add new numbers to this for myNumber in myNumbers: validDividers = [] # In this list we will put all the valid dividers for myDivider in myDividers: if not (myNumber % myDivider): validDividers.append(myDivider) if validDividers: # This means that the list has to have values in it print("Number {} is divisible by {}".format(myNumber,validDividers)) The output is not very nice here as you print off the list with the square brackets, you could try the following bit of code under the if validDividers: condition: if validDividers: # This means that the list has to have values in it # First make strings out of the integers; this is valid Python syntax where you make a list out of a list validDividerStrings = ["{}".format(validDivider) for validDivider in validDividers] # Now you can join the elements of a list (if they are strings) together using the .join() method for a string: validDividerString = ', '.join(validDividerStrings) print("Number {} is divisible by {}".format(myNumber,validDividerString)) |
Write a program where you find, for each positive number up to 50, all numbers that can divide each number. [click on show more for answer) |
---|
myNumbers = range(1,51) for x in myNumbers: dividers = [] for y in range(1,x+1): if not (x % y): dividers.append(y) for divider in dividers: print ("Number {} can be divided by {}!".format(x,divider)) The output is again not very nice here, you can replace the last two lines by this for nicer output: dividerText = ", ".join([str(divider) for divider in dividers]) print ("Number {} can be divided by {}!".format(x,dividerText)) |
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
Try to reproduce a for: loop (the example of numbers divisible by 17) by using a while: loop. [click on show more for answer) |
---|
myNumber = 1 myDivider = 17 while myNumber <= 500: if not (myNumber % myDivider): # Nothing left after division, so number is divisible. print("Number {} can be divided by {}!".format(myNumber,myDivider)) myNumber += 1 |
Write a program where you start with a list of numbers from 1 to 100, and you then remove every number from this list that can be divided by 3 or by 5. Print the result. [click on show more for answer) |
---|
myNumberList = range(1,101) # You have to make a copy of the original list here, otherwise Python will get 'confused' # when you remove values from the list while it's looping over it for number in myNumberList[:]: if not (number % 3) or not (number % 5): myNumberList.pop(myNumberList.index(number)) print myNumberList |
Write a program where you ask the user for an integer (whole number), and keep on asking if they give the wrong input. Check whether the number can be divided by 7, and print the result. [click on show more for answer) |
---|
myNumberList = range(1,101) # Keep on checking until you have a number, prime the while loop as well isNumber = False while not (isNumber): inputString = input("Give a number:") if inputString.isdigit(): isNumber = True number = int(inputString) else: print("Incorrect, not a whole number, try again.") if not (number % 7): print("{} can be divided by 7!".format(number)) |