Loops¶
Consider the code below: It prints the numbers 1 through 10 using what we've learned so far.
This notebook is about how to do the same task less tediously. Loops are a way to repeatedly execute some code, in a simple and succinct way.
print(1)
print(2)
print(3)
print(4)
print(5)
print(6)
print(7)
print(8)
print(9)
print(10)
Indeed, we can use a for loop to do the same in only two lines:
#pseudo code
for number in number_list:
print number
number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#the variable number is initialized inside the for statement.
#You do not need to declare it before. It will continue to exist after the loop.
for number in number_list:
print(number)
print("Now we are done.")
print("What is number now?", number)
Loops are part of flow control. The code inside the loop is (usually) executed several times, whereas lines such as above are only executed one time. The program also needs to know when the loop is over and we return to 'linear' flow. Like in if
blocks, this is made clear with indentation.
for
loops¶
In Python, for
loops are written like this:
for variable in sequence:
this code is executed inside the loop
and this code too
now we are not in the loop anymore
Read: for each *variable* in *sequence, execute the expression* (that is code you want to repeat for each variable)
variable
is a variable and can be called whatever you want.sequence
is a sequence we iterate over. It is some kind of collection of items, for instance: astr
of characters, arange
, a list etc.variable
references the current position of our *iterator* within the iterable variable. It will iterate over (run through) every item of the collection and then go away when it has visited all items.The body of the loop is indented.
When we write a command on the same indentation level as the
for
statement the loop is over. This will be executed after the loop.
for
loops with ranges¶
Instead of writing out a list with numerical value we can create it using a range:
for number in range(1, 11):
print(number)
range()
function¶
The range()
function returns a sequence of numbers, starting from 0 by default, and increments by 1 by default, and stops at a specified number (which is not included in the range).
Based on what we learned so far you might think that it creates a list, but it does not. In fact, range does not do anything by itself, but can be used inside a for loop to create the sequence to loop over.
The syntax is:
range(start, stop, step)
The step parameter tells the function how many steps to skip and which direction to count (+
for up and -
for down).
Examples:
range(8)
gives you integers from 0 through 7.range(2, 9)
will give you integers from 2 to 8.range(10, 20, 2)
will give you even numbers from 10 to 18. Remember, the upper limit of the range is excluded!range(9, 0, -1)
will start from 9 and give you integers down to 1.
#try it out!
Another useful function for for loops is enumerate
. It will create a list of tuples where the second element is the current item and the first element is its position:
#try it out!
countries = ['Denmark', 'Spain', 'Italy']
# iterate over the ountries as we did with the list of numbers above:
for country in countries:
print(country)
# get both items and their position
for index, country in enumerate(countries):
print("My number" + str(index) + " favorite country is: " + country)
Exercise 1¶
~ 20 minutes
a. Use a for loop to iterate over range(4)
. Which numbers does it produce?
# your code goes here
b. Now write a for loop using range
that produces the numbers 1 to 4.
# your code goes here
c. What numbers does the following range generate inside a for loop? Write out the loop to check.
range(12,0,-3)
# your code goes here
d. Loop through numbers 1-20:
- If the number is 4 or 13, print "x is unlucky"
- Otherwise:
- If the number is even, print "x is even"
- If the number is odd, print "x is odd"
check
Conditions.ipynb
e. In the code below we're counting from 0 as python usually does. Can you fix so that it starts writing from 1?
# get both items and their position
for index, country in enumerate(countries):
print("My number" + str(index) + " favorite country is: " + country)
while
loops¶
We can also iterate over a sequence using a while
loop, which has a different format:
while condition:
expression
while
loops continue to execute while a certain condition is True
, and will end when it becomes False
.
user_response = "Something..."
while user_response != "please":
user_response = input("Ah ah ah, you didn't say the magic word: ")
while
loops require more careful setup than for
loops, since you have to specify the termination conditions manually.
Be careful! If the condition doesn't become False
at some point, your loop will continue *forever*!
my_float = 50.0
while my_float > 1:
my_float = my_float / 4
print(my_float)
Exercise 2¶
~15 minutes
a. What does the following loop do?
i = 1
while i < 5:
i + i
print(i)
Hint: is the value of
i
changing?
# your code goes here
b. What does the following loop do?
i = 0
while i <= 5:
i = i + 1
print(i)
# your code goes here
c. Fix the infinite loop below so that it doesn't run endlessly anymore:
# this code runs forever...
x = 0
while x != 11:
x += 2
print(x)
# your code goes here
Python loop control¶
Controlled exit, skipping a block of code, or ignoring external factors that might influence your code, can be achieved with the Python statements: break
, continue
, and pass
.
*break
* statement¶
The keyword break
gives us the ability to exit out of a loop whenever we want, and can be used in both while
and for
loops.
Example:
for letter in 'Python':
if letter == 'h':
break
print('Current Letter:', letter)
The break
statement needs to be within the block of code under your loop statement, ususally after a conditional if
statement.
for letter in 'Python':
if letter == 'h':
break
print('Current Letter :', letter)
*continue
* statement¶
The continue
statement in Python gives you the option to skip over the part of a loop where a condition is met, but to go on to complete the rest of the loop. That is, it disrupts the iteration of the loop that fulfills the condition and returns the control to the beginning of the loop. It works with both while
and for
loops.
Example:
for letter in 'Python':
if letter == 'h':
continue
print('Current Letter :', letter)
The difference in using continue
rather than break
is that the loop will continue despite the disruption when the condition is met.
for letter in 'Python':
if letter == 'h':
continue
print('Current Letter :', letter)
for letter in 'Python':
if letter == 'h':
pass
print('Current Letter :', letter)
Exercise¶
~ 15 minutes
Write a loop that:
- iterates over each character in the string
"I live in CPH, and I like it here."
; - for each character checks if it is a space;
- if it is a space, then just continue with the loop;
- if the character is not a space, do the following:
- check if it is a comma
,
; - if the character is a comma
,
, break the loop; - if the character is not a comma, print it.