For this lesson we will be learning about various looping functions that python has to offer. A loop in a program is something that occurs whilst something meets a set of requirements. For example we might want to takeaway one number from another until it is down to zero, sort of like a counter. So for that we could write:
counter = 10
while (counter > 0):
print ‘This is a counter no:’, counter
counter = counter – 0
print ‘end of loop’
The above has a variable, counter set at the number 10. While the counter is greater than (the > sign) 0, the code below that is indented will run until the counter is no longer greater than zero. Following that, the program will print ‘end of loop’.
Below shows the output from the programming lab if you were to create this code:
A while loop will always loop whilst the condition is met. Therefore after 10 loops, it will no longer print out the counter number and will break from the loop. This is when the end of loop is printed. A while loop is useful for when you do not know how many times you will need to loop. If you do know how many times you will need to loop it would be better to use a for loop. If the condition never changed, for example we didn’t take away one from counter each time, the loop would go on forever. This is known as an infinite loop.
Lists:
In Python, we can declare a list. A list can contain a multiple number of objects and these can then be used throughout programs, much like a collection of variables. We will go further into lists in lesson 7 however you must understand that a list is a collection of variables for the for loop example. The starting point of a list is always 0, therefore in the below code, sherbet lemon is in section 0 of the list. A 10 part list will go from 0-9.
For Loops:
The above code shows a for loop that will print the current sweet in a list until it gets to the end of the list. It will then say good bye. The code operates on a principle that for all the sweets in the list sweets, it will print out each sweet’s name as well as current sweet preceding it. For loops can be particularly useful when dealing with lists.
Recent Comments