Before session 1
There are a few significant differences between Python 2 and Python 3 (if you have used Python 2 somewhere, please check for the differences, especially regarding the print function, division and user input).
Please download and install Thonny from: https://github.com/thonny/thonny/releases/download/v3.3.13/thonny-3.3.13.exe
If you have problems with installation, please look at: https://github.com/thonny/thonny/wiki/Windows
Please download and install Thonny from: https://github.com/thonny/thonny/releases/download/v3.3.13/thonny-3.3.13.pkg
If you have problems with installation, please look at: https://github.com/thonny/thonny/wiki/MacOSX
Nested lists and nested loops
We have studied single (not nested) lists and loops in the course Introduction to Programming I. Actually, lists can be used inside lists (list elements are other lists) and loops can be created inside loops. Please read this material before session 1. While reading, study the code, run it, change it and rerun it!
A nested list is a list which is placed inside of another list. In the following example, the element with index 3 is a nested list:
nested = ["hello", 2.0, 5, [10, 20]]
If we output the element with index 3
nested = ["hello", 2.0, 5, [10, 20]] print(nested)
To extract an element from the nested list, we have to take two steps:
elem = nested print(elem) #the result is 10
Or merge the steps as:
print(nested) #the result is 20
Bracket operators evaluate the indexes from left to right. In the example nested, Python looks for the fourth element (with index 3) of list and extracts the second element (with index 1) of the nested list.
Nested lists are often used to represent matrices. For example, the matrix:
might be represented as:
mx = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
mx is a list with three elements, where each element is a row of the matrix. We can select an entire row from the matrix:
print(mx) #the result is [4, 5, 6]
Or we can extract a single element from the matrix using the double-index notation:
print(mx) #the result is 6
The first index points to the row, and the second index points to the column.
Although this way of representing matrices is common, it is not the only one. Later we will learn about dictionaries.
The next questions are meant for self-assessment. Try to figure out the correct answer. Also, it is useful to look at the explanations for wrong answers as well.
Python allows using one loop inside another loop. A nested loop is a loop that is placed inside the body of another loop. The following lines summarise the main concepts of the inner and outer loops:
for [first iterating variable] in [outer loop]: # Outer loop [do something] # Optional for [second iterating variable] in [nested loop]: # Nested loop [do something] [do something] # Optional
At first, the program executes the first iteration of the outer loop. The first iteration triggers the inner, nested loop. The inner loop runs through all its iteration till the end. Then the program returns back to the outer loop. The second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes or a break or another statement disrupts the process.
Implement a nested for loop in order to have a closer look at it. In this example, the outer loop iterates through a list of integers called num_list, and the inner loop iterates through a list of strings called alpha_list.
num_list = [1, 2, 3] alpha_list = ['a', 'b', 'c'] for number in num_list: print(number,end=" ") for letter in alpha_list: print(letter,end=" ")
The output of the program is:
1 a b c 2 a b c 3 a b c
The output illustrates that the program completes the first iteration of the outer loop by printing 1, which then triggers the inner loop, printing a, b, c, consecutively. Once the inner loop is completed, the program returns to the outer loop, prints 2, then again executes the inner loop in its entirety (a, b, c) etc.
Nested for loops can be used for iterating through the items within lists composed of lists (matrices). In other words, if we employ just one for loop in a matrix, the program will output each internal list as one element:
mx = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for list in mx: print(list)
[1, 2, 3] [4, 5, 6] [7, 8, 9]
In order to access each element of the internal lists, a nested for loop is utilised:
mx = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for list in mx: for item in list: print(item, end=" ")
1 2 3 4 5 6 7 8 9
Moreover, the nested loops are often used to loop over the nested lists. It is an old tradition, to use i as an iteration variable of the outer loop and j as an iteration variable of the inner loop. Study the following example:
mx = [[1, 2, 3, 4], [5, 6], [7, 8, 9]] for i in range(len(mx)): for j in range(len(mx[i])): print(mx[i][j], end=" ") print()
The outer loop passes row by row, i takes the values in the range between 0 and len(mx) - 1. The inner loop takes the values from the current row mx[i]. The elements mx[i][j] depend on the value of j, which is between 0 and len(mx[i]) - 1. Importantly, the program works irrespectively from the size of the row size - the iteration variable j take the value of the current row length.
One more example of nested for loop:
for x in range(1, 11): for y in range(1, 11): print(x*y,"\t",end=" ") print()
Finally, consider the syntax of a nested while loop:
while [expression of outer loop]: # Outer loop [do something] # Optional while [expression of nested loop]: # Nested loop [do something] [do something] # Optional
A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa.
Go to Moodle and take the first test. Note that each test gives you up to 2 points. You can answer each question several times. Also, you can take each test several times during a week.
Exercise 1. Meal calories
The deadline is Friday, the 12th of November, 19:00 (Estonian time).
The caloric value of food shows how much energy your body gets from the carbohydrates, proteins and fats that the food contains. The file calories.txt contains different meals on separate lines. The number of carbohydrates, proteins and fats is given for each meal in grams. It is known that
- 1 g of carbohydrate gives 4 Kcal,
- 1 g of protein gives 4 Kcal,
- 1 g of fat gives 9 Kcal.
Write a program that calculates and outputs how many calories all meals together give.
If the file calories.txt contains the following lines:
40 53 14 62 47 26 49 43 20 10 35 22
then the output of the program should be
Go to Moodle and upload your solution into Homework 1.