Before session 10
1. Short mid-term summary of the course
Review the material of the course.
2. Test
Go to Moodle and take the test. The test covers basic concepts of the course.
3. Solve and submit
Write a program that asks the user about a dish for lunch and outputs information about the restaurants in Tartu where this dish is served along with the prices of the dish and some statistics about the prices in general.
Information about restaurants in Tartu, dishes and prices should be saved in the file food.txt – each entry on a separate line. An example of the file is shown below:
Entri - fish, 3 Vilde - fish, 3.5 Vilde - chicken, 3.5 Vilde - soup, 2 Shakespeare - meat, 4 Pierre - chicken, 4.5 La Dolce Vita - soup, 3.2 Werner - salad, 3.5 Werner - meat, 5.5 Big Ben - fish, 4
If the user asks for fish, the program outputs (user inputs are in italics):
What dish would you like to have? fish You can have fish in Entri for 3 EUR. You can have fish in Vilde for 3.5 EUR. You can have fish in Big Ben for 4 EUR. Difference between minimum and average prices is 0.5 EUR. Minimum price 3 EUR is in Entri. Average price is 3.5 EUR.
If the user asks for something that is not noted in the file (e.g. sushi), the program outputs:
What dish would you like to have? sushi This dish is not served in restaurants of Tartu.
Your program should meet both the requirements and the output format stated in the task/examples. To solve the task, go through the following steps:
- Write a program which opens the file food.txt. If the file does not exist, then the program nicely finishes its work and does not crash (use try-except).
- Prompt the user for a dish he/she would like to have for lunch (no special input checks are required).
- The program has to go through the file line by line and check if the line corresponds to the entered dish. If so, the program outputs information about the restaurant, the dish, and the price.
- Create two lists: one for the restaurants and the other one for the prices. Add data about the entered dish into the lists.
- If the file is read and the lists are empty (the queried data have not been found in the file), then the program outputs a corresponding message.
- Write a function minprice that takes the price list and the restaurant list as its arguments and prints out the minimum price and the name of the restaurant which serves the cheapest dish the user queried.
Hint: First, find the minimum price from the list and then make a loop and find the position of the minimum price in the price list (the corresponding restaurant has the same position in the restaurants list).
- Write a function avgprice that takest the price list as an argument and returs average price.
- Write a function pricerange that takes the price list as an argument and returns the difference between minimum and average prices.
- If the file contains any data about the entered dish, the program calls the function pricerange and outputs the result.
- Call the functions minprice and avgprice after printing out the price range.
Go to Moodle and upload your solution under homework for session 10.
4. Nested lists and nested loops
So far we have studied single (non-nested) lists and loops. Actually, lists can be used inside lists (list elements are other lists) and loops can be created inside loops.
Please read this material before the session. While reading, study the code, run it, change it and rerun it!
Nested lists
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[3])
we get [10, 20].
To extract an element from the nested list, we have to take two steps:
elem = nested[3] print(elem[0]) # the result is 10
Or merge the steps as:
print(nested[3][0]) # the result is 10
Bracket operators evaluate the indexes from left to right. In the example nested[3][0], Python looks for the fourth element (with index 3) of list and extracts the first element (with index 0) of the nested list.
Matrices
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]]
Here, 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[1]) # the result is [4, 5, 6]
Or we can extract a single element from the matrix using the double-index notation:
print(mx[1][2]) # 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.
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.
Nested loops
Python allows to use one loop inside another loop. A nested loop is a loop that is placed inside the body of another loop. The following lines summarise main concepts of 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 until 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 other statement disrupts the process.
The next example gives a closer look to nested for loop. Here, 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 this 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)
Output:
[1, 2, 3] [4, 5, 6] [7, 8, 9]
In order to access each element of the internal lists, a nested for loop is used:
mx = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for list in mx: for item in list: print(item, end=" ")
Output:
1 2 3 4 5 6 7 8 9
Moreover, nested loops are often used to loop over 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. Consider 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 of row size – iteration variable j takes 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()
Also, programs can use nested while loops with analogous syntax:
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.