Week 4
Control - while and for
Control
While
While loops allow us to do something while a condition is met - providing the first statement which can drastically control the flow of our program. The syntax for these is very similar if statements, with the important distinction that the code inside runs continuously until the condition becomes False:
It's important to note that if the condition never becomes false, then the loop will run forever!
In this case, you can abort with ctrl+c (in the console) or by pressing the stop button in most IDEs.
Here's an example of how we can use a "counter" with a while loop:
And an example of waiting for a correct user input:
We can use and/or to make the while statement's loop condition more sophisticated. For example, we could allow users to type their passwords in up to three times.
Notice, however, that in this example we don't know why we left the while loop, as it can occur as a result of the user entering the correct password, or having tried too many times. This means we'd need to add additional if statements below. (this can be circumvented by using break statements
We often use while statements to do things a certain number of times (again, using a counter):
Finally, we can use such counters to loop through lists using a while statement:
But there is a far more natural way of looping through lists in python:
For
A far more elegant way of looping through data structures that contain some number of elements is to use "for" loops. Think of these as "for each item in data structure"
The same syntax can also be used on dictionaries (and other "iterable" objects) - going through the keys by default
Range
The python range() function gives us a useful way of creating a list of numbers. Note: the function returns integers ranging from the first parameter to the second, but not including the second!
Technically range doesn't actually create a list data structure, as such, if you want to create a list of number by using range, you'll need to typecast using list()
Here's an example of using a for loop with range, to print even numbers in a range:
And here's a better way (there often is one!):
Length
If we want to find out how many items are in a data structure we can use the length function, len():
Duplicate Search
Here's an example making use of nested for loops to find duplicated items in a list -> Here we explicitly use range(len()) so that we can index the list, rather than access its items. We do this because we want to avoid checking the same list index against itself (as this will always be equal):
Last updated