In programming, looping means repeating the same set of computations in the same sequence for a number of times.
Iteration means executing the same block of code over and over, potentially many times. A programming structure that implements iteration is called a loop.
For example if you wanted to perform the same operation on each item in a list you could use a loop to iterate over the list and perform that task, or if you wanted to produce a given output while a certain condition met you can also use a loop.
Computers are great at performing repetitive tasks over and over, as they never “get bored” or make mistakes.
In programming, loop is a logical structure that repeats a sequence of instructions until certain conditions are met. Looping allows for repeating the same set of tasks on every item in an iterable object, until all items are exhausted or a looping condition is reached.
An iterable is an object capable of returning its members one by one. Said in other words, an iterable is anything that you can loop over with a for loop in Python.
Looping is applied to iterables — objects that store a sequence of values in specific data formats such as dictionaries. The beauty of loops is that you write the program once and use it on as many elements as needed.
So what can we loop over? Basically, any data type that is iterable. Iterable objects in Python are a sequence of values stored in different kinds of data formats such as:
Lists : Example: [2,4,7,8]
Tuples : Example: (2,4,7,8)
Dictionaries : Example: {"Name":"Kev","Age":25,"Gender":"Male"}
Strings : Example: "Data Science"
In programming, there are two types of iteration, indefinite and definite:
Indefinite : With indefinite iteration, the number of times the loop is executed isn’t specified explicitly in advance. Rather, the designated block is executed repeatedly as long as some condition is met.
Definite : With definite iteration, the number of times the designated block will be executed is specified explicitly at the time the loop starts.
Two kinds of loops you will mainly encounter: for
loop and while
loop. Among them, for loops are the most common kind applied in data science problems. The key differences are:
for
loops iterate a finite number of times for each element in the iterable object
while
loops keep going until a certain condition is met. i.e number of times to iterate is not specified in advance
This technique instructs the computer to continuously execute a code based on the value of a condition. It begins with the keyword while
, followed by a comparison to be evaluated, then a colon. On the next line is the code block to be executed, indented to the right. Similar to an if statement, the code in the body will only be executed if the comparison is evaluated to be true.
In a while loop the indented code block will keep executing as long as the evaluation statement is true. Once the statement is no longer true, the loop exits and the next line of code will be executed.
A while loop will repeat the instructions within the indented block of code as long as the initial condition that created the loop remains true:
while
expression:
statement(s)
statement(s) represents the block to be repeatedly executed, often referred to as the body of the loop. This is denoted with indentation, just as in an if statement.
The controlling expression, expression
, typically involves one or more variables that are initialized prior to starting the loop and then modified somewhere in the loop body.
When a while loop is encountered, expression
is first evaluated in Boolean context. If it is true, the loop body is executed. Then expression
is checked again, and if still True
, the body is executed again. This continues until expression
becomes False
, at which point program execution proceeds to the first statement beyond the loop body.
Consider the following example:
# example 1
i = 0 # initializing variable
while i < 5:
print("Iteration Number: ", i)
i = i + 1 # incrementing variable
# i += 1
print("Most recent value of i is: ",i)
Iteration Number: 0 Iteration Number: 1 Iteration Number: 2 Iteration Number: 3 Iteration Number: 4 Most recent value of i is: 5
Let’s go through each line of code inside the above loop:
In the first line we’re assigning the value of 0 to the variable i
. This action is called initializing, in order to give an initial value to a variable. The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 0.
In the line after that, we’re starting the while loop. We’re setting a condition for this loop that i
needs to be smaller than 5. Right now, i
is 0 since it’s just been initialized, so this condition is currently true.
On the next two lines, we have a block that’s indented to the right. Here, we can use the characteristic shared with Python functions, which indicates that every line of code that shares the same amount of indented spaces will be part of the body of the function, or loop in this case.
There are two lines in the body of the loop. In the first line, we print a message followed by the current iteration, represented by the value of i
. In the second line, the value of i
is incremented. We do this by adding 1 to its current value and assigning it back to i
. So after the first execution of the body of the loop, i
will be 1 instead of 0.
When the body of the loop (indented block) has finished, program execution returns to the top of the loop, and the expression is evaluated again. If it is still true, the body executes again.
Because this is a loop, the computer doesn’t just continue executing with the next line in the script. Instead, it loops back around to re-evaluate the condition for the while loop.
The computer will keep doing this until the condition isn’t true anymore. In this example, the condition will be false when i
is no longer smaller than 5. Once the condition is False, the loop finishes, and the next line of the code is executed.
# example 2
n = 5
while n > 0:
n = n-1
print(n)
4 3 2 1 0
# example 3
a = ["foo", "bar", "baz"] # a list
while a:
print(a)
a.pop(-1)
['foo', 'bar', 'baz'] ['foo', 'bar'] ['foo']
When a list is evaluated in Boolean context, it is truthy if it has elements in it and falsy if it is empty. In this example, a
is true as long as it has elements in it. Once all the items have been removed with the .pop()
method and the list is empty, a
is false, and the loop terminates.
while
loops use the condition to check whether to exit from the loop structure. The body of the while loop needs to make sure that the condition being checked will change. If it doesn’t change, the loop may never finish and we get what’s called an infinite loop, a loop that keeps executing and never stops.
# example 4
i = 0 # initialize variable
while i < 5:
print(i) # forgot to increment i in the loop body
As in the previous case, we initialized the i
variable, but forgot to add an index inside the loop to refresh the variable in each iteration. As a consequence, the loop will run until we manually interrupt it with the CTRL+C commands
In order to avoid this issue, it’s a good idea to take a moment to consider the different values a variable can take. This helps you make sure the loop won’t get stuck during the iteration.
break
and continue
keywords¶To avoid execution of the entire body of a while
loop, Python provides two keywords that terminate a loop iteration prematurely:
break
: immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body. With the break
statement we can stop the loop even if the while condition is true
continue
: immediately terminates the current loop iteration. Execution jumps to the top of the loop, and the controlling expression is re-evaluated to determine whether the loop will execute again or terminate. With the continue
statement we can stop the current iteration, and continue with the next
# example 5
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
1 2 3
# example 6
# To skip over a certain iteration of the while loop you could also use the continue statement.
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
1 2 4 5 6
# example 7
"""
Given a list sorted in descending order,
you want to calculate the total/sum of all positive elements of the list
"""
given_list = [7,6,5,4,4,3,1,-1,-2,-4]
# sum of all negative numbers
i = 0
total = 0
while given_list[i] > 0:
total += given_list[i]
i += 1
print(total)
30
# example 8
"""
Given a list sorted in descending order,
you want to calculate the total/sum of all positive elements of the list
"""
given_list = [7,6,5,4,4,3,1,-1,-2,-4]
total = 0
i = 0
while True:
if given_list[i] <= 0:
break
total += given_list[i]
i += 1
print(total)
30
For
Loops¶A for
loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
With the for
loop we can execute a set of statements, once for each item in a list, tuple, set etc.
A for
loop iterates over a sequence of values.
for
itemin
iterable:
statements(s)
Notice that the structure is kind of similar to the structures of while loops.
The first line indicates the distinguishing for
keyword and it ends with a colon.
The body of the loop is indented to the right, like in the while loop, the if block, and the function definitions.
What’s different in this case is that we have the keyword in
.
Also, between the for
keyword and in
keyword, we have the name of a variable, in this case item
. This variable will take each of the values in the sequence that the loop iterates through.iterable is a collection of objects—for example, a list or tuple. The statement(s) in the loop body are denoted by indentation, as with all Python control structures, and are executed once for each item in iterable. The loop variable item takes on the value of the next element in iterable each time through the loop.
# example 9
fruits = ["mango","orange","passion","straw berry","apple","pineapple"]
for fruit in fruits:
print("I want a ", fruit)
I want a mango I want a orange I want a passion I want a straw berry I want a apple I want a pineapple
# example 10
# loop over a string
for char in "banana":
print(char)
b a n a n a
# example 11
# compound for loop
for char in 'banana':
upper_char = char.upper()
print(upper_char)
B A N A N A
As seen before in the while
loop, you can use break
and continue
to control iterations
# example 12
fruits = ["mango","orange","passion","straw berry","apple","pineapple"]
# stop iterations once you find a straw berry
for fruit in fruits:
print("I want a ", fruit)
if fruit == "straw berry":
break
I want a mango I want a orange I want a passion I want a straw berry
# example 12
fruits = ["mango","orange","passion","straw berry","apple","pineapple"]
# suppose you want all fruits except passion
for fruit in fruits:
if fruit == "passion":
continue
print("I want a ", fruit)
I want a mango I want a orange I want a straw berry I want a apple I want a pineapple
Range items are a special type of sequences and usually helps to define ranges or intervals to review.
Usually, when defining a range you can define a range of another sequence data type by noting the start (where to start), stop (where to end), and step (number of instances between each item) which you are looking to investigate. These come in handy when defining how you want to loop through a sequence with more complex logic.
Suppose we want to iterate over all numbers between 0 and 20:
# example 13
for i in range(0,20): # 20 is not included
print(i)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# example 14
"""
sum of all numbers in the interval 10 - 20 (inclusive)
"""
total = 0
for i in range(10,21):
total += i
print("Total of numbers ",total)
Total of numbers 165
Dictionaries in Python are a collection of key-value pairs — meaning, every item in the dictionary has a key and an associated value.
# example 15
guy = {'name':'John','surname':'Doe','age':45,'dog':False, 'cat':True, 'children':['Jane','Steve','Mary']}
for info in guy: # will return the keys
print(info)
name surname age dog cat children
# example 16
guy = {'name':'John','surname':'Doe','age':45,'dog':False, 'cat':True, 'children':['Jane','Steve','Mary']}
for guy_info in guy.values():
print(guy_info)
John Doe 45 False True ['Jane', 'Steve', 'Mary']
# example 17
"""
to retrieve both keys and values from a dictionary
"""
guy = {'name':'John','surname':'Doe','age':45,'dog':False, 'cat':True, 'children':['Jane','Steve','Mary']}
for key, val in guy.items():
print("Key:", key)
print("Value:", val)
print("")
Key: name Value: John Key: surname Value: Doe Key: age Value: 45 Key: dog Value: False Key: cat Value: True Key: children Value: ['Jane', 'Steve', 'Mary']
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop"
# example 18
list_a = [1,2,3,4]
list_b = ['a','b','c']
for num in list_a:
for char in list_b:
print(num, char)
print(" ")
1 a 1 b 1 c 2 a 2 b 2 c 3 a 3 b 3 c 4 a 4 b 4 c
# example 19
# defining two lists
colours = ["red", "blue", "yellow","green","orange"]
clothes = ["shirt", "socks"]
for x in colours: # first, we'll go over the first list
for y in clothes: # now, we'll go over the second one
print(x, y)
red shirt red socks blue shirt blue socks yellow shirt yellow socks green shirt green socks orange shirt orange socks
For example, suppose that you have to prepare the schedule for a world cup tournament with four of our favorite national teams that will play against each other.
what we don’t want to do is have a team/country play against itself. To do this, we need to use a conditional that makes sure we only print the pairing when the countries are different.
# example 20
nations = ["Brazil", "Portugal", "Spain", "Germany", "Ghana"]
for nation in nations:
for _nation in nations:
if nation != _nation:
print(nation, "vs", _nation)
Brazil vs Portugal Brazil vs Spain Brazil vs Germany Brazil vs Ghana Portugal vs Brazil Portugal vs Spain Portugal vs Germany Portugal vs Ghana Spain vs Brazil Spain vs Portugal Spain vs Germany Spain vs Ghana Germany vs Brazil Germany vs Portugal Germany vs Spain Germany vs Ghana Ghana vs Brazil Ghana vs Portugal Ghana vs Spain Ghana vs Germany
else
Clause¶Python allows an optional else
clause at the end of a loop.
The else
clause will be executed only if the loop terminates by exhaustion that is, if the loop iterates until the controlling condition becomes false. If the loop is exited by a break
statement, the else clause won’t be executed.
# example 21
nations = ["Brazil", "Portugal", "Spain", "Germany", "Ghana"]
for nation in nations:
print(nation)
else:
print("Done Printing")
Brazil Portugal Spain Germany Ghana Done Printing
# example 21
nations = ["Brazil", "Portugal", "Spain", "Germany", "Ghana"]
for nation in nations:
if nation == "Portugal":
break
print(nation)
else:
print("Done Printing")
Brazil
# example 22
fruits = ["mango","orange","passion","straw berry","apple","pineapple"]
i = 0
while i < len(fruits):
fruit = fruits[i]
print("I'm looking for an apple. Once I find it, i'll stop looking.")
print(fruit)
if fruit == "apple":
print("I found an apple!")
break
i+=1
else:
print("There was no apple in the list")
I'm looking for an apple. Once I find it, i'll stop looking. mango I'm looking for an apple. Once I find it, i'll stop looking. orange I'm looking for an apple. Once I find it, i'll stop looking. passion I'm looking for an apple. Once I find it, i'll stop looking. straw berry I'm looking for an apple. Once I find it, i'll stop looking. apple I found an apple!
# example 23
fruits = ["mango","orange","passion","straw berry","pineapple"]
j = 0
while j < len(fruits):
fruit = fruits[j]
print("I'm looking for an apple. Once I find it, i'll stop looking.")
print(fruit)
if fruit == "apple":
print("I found an apple!")
break
j+=1
else:
print("There was no apple in the list")
I'm looking for an apple. Once I find it, i'll stop looking. mango I'm looking for an apple. Once I find it, i'll stop looking. orange I'm looking for an apple. Once I find it, i'll stop looking. passion I'm looking for an apple. Once I find it, i'll stop looking. straw berry I'm looking for an apple. Once I find it, i'll stop looking. pineapple There was no apple in the list
pass
Statement¶pass
doesn’t do anything, it is just a placeholder for a statement that hasn’t been written yet.
If we don’t put a pass
in the indented block after the :
, it will throw an error message and the rest of the code will not execute.
for i in range(5):
# you will implement some code here
Input In [42] # you will implement some code here ^ SyntaxError: unexpected EOF while parsing
for i in range(5):
# you will implement some code here
pass
k = 0; n=0
while k < n:
# will implement code later
pass
List comprehensions are a way to construct new lists out of existing lists after applying transformations to them.
Every list comprehension has an output (usually but not necessarily transformed) and a for loop, and is surrounded by square brackets. Square brackets are used because we are constructing a list.
To construct a set or tuple, enclose the list comprehension with {}
or ()
respectively.
[transformed_l for l in list]
# example 24
# create a list of integers between 1 and 5
my_lst = [i for i in range(1,6)] # using a list comprehension
print(my_lst)
[1, 2, 3, 4, 5]
# example 25
# create a list of integers between 1 and 5 using a for loop
my_lst = []
for i in range(1,6):
my_lst.append(i)
print(my_lst)
[1, 2, 3, 4, 5]
# example 26
# create a list of all even numbers between 0 and 10
# using for loop
even_nums = []
for num in range(10):
if num % 2 == 0:
even_nums.append(num)
print(even_nums)
[0, 2, 4, 6, 8]
# example 27
# using a list comprehension
even_nums = [i for i in range(10) if i % 2 == 0]
print(even_nums)
[0, 2, 4, 6, 8]
# example 28
# replace all odd numbers with the word odd, else use the number
nums = [num if num % 2 == 0 else 'Odd' for num in range(10)]
print(nums)
[0, 'Odd', 2, 'Odd', 4, 'Odd', 6, 'Odd', 8, 'Odd']
given_list = [3,7,9,15,4,15,17,2]
total_even = 0 # initialize variable for sum
for num in given_list:
if num % 2 == 0:
total_even += num
print(total_even)
6
# total of both even and odd numbers
given_list = [3,7,9,15,4,15,17,2]
total_even = 0 # initialize variable for sum of even numbers
total_odd = 0 # initialize variable for sum of odd numbers
for element in given_list:
if element % 2 == 0:
total_even += element
else:
total_odd += element
print("Total of even numbers: ", total_even)
print("Total of odd numbers: ", total_odd)
Total of even numbers: 6 Total of odd numbers: 66
# number of both even and odd numbers
given_list = [3,7,9,15,4,15,17,2]
count_even = 0 # initialize variable for count of even numbers
count_odd = 0 # initialize variable for count of odd numbers
for element in given_list:
if element % 2 == 0:
count_even += 1
else:
count_odd += 1
print("Number of even numbers: ", count_even)
print("Number of odd numbers: ", count_odd)
Number of even numbers: 2 Number of odd numbers: 6
zip
functioncountries = ["USA","China","Germany","Egypt","Japan","India"]
cities = ["Washington DC", "Beijing", "Berlin", "Cairo", "Tokyo", "New Delhi"]
print(list(zip(countries, cities)))
[('USA', 'Washington DC'), ('China', 'Beijing'), ('Germany', 'Berlin'), ('Egypt', 'Cairo'), ('Japan', 'Tokyo'), ('India', 'New Delhi')]
countries = ["USA","China","Germany","Egypt","Japan","India"]
cities = ["Washington DC", "Beijing", "Berlin", "Cairo", "Tokyo", "New Delhi"]
for country, city in zip(countries, cities):
print(city, "is in", country)
Washington DC is in USA Beijing is in China Berlin is in Germany Cairo is in Egypt Tokyo is in Japan New Delhi is in India
Write a program that checks if a number from input is a multiple of three, five and both three and five.
For multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".
Complete the fizz buzz challenge for all numbers between 0 and 199. For numbers greater than 99 use print the words FIZZ, BUZZ, FIZZ BUZZ in upper case.
We solved this in the previous class. Now use it in a loop.
# solution for fizz buzz
# check if num is multiple of both 3 and 5
if (num % 5 == 0 and num % 3 == 0):
# multiple of both 3 and 5
print("FizzBuzz")
# check if num is multiple of 3
elif num % 3 == 0:
# multiple of 3
print("Fizz")
# check if num is multiple of 5
elif num % 5 == 0:
# multiple of 5
print("Buzz")
# Your solution here
# Your solution