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://bitbucket.org/plas/thonny/downloads/thonny-2.1.22.exe
If you have problems with installation, please look at: https://bitbucket.org/plas/thonny/wiki/Windows
Please download and install Thonny from: https://bitbucket.org/plas/thonny/downloads/thonny-2.1.22.dmg
If you have problems with installation, please look at: https://bitbucket.org/plas/thonny/wiki/MacOSX
Short summary of the course Introduction to Programming I
Go to Moodle and take the first test. The test is based on the basic concepts from the course Introduction to Programming I.
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. The last attempt is saved and counted as the final score for the quiz.
Before our first practice session in class, you have to solve the exercise based on the material from the course Introduction to Programming I.
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 price of the dish and some statistics about the prices in general.
The information about Tartu restaurants, 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:
fish;Entri;3 fish;Vilde;3.5 chicken;Vilde;3.5 soup;Vilde;2 meat;Shakespeare;4 chicken;Pierre;4.5 soup;Werner;3.2 salad;Werner;3.5 meat;Werner;5.5 fish;Big Ben;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. The difference between max and min prices is 1.0 EUR. The maximum price is in Big Ben (4 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 Tartu restaurants.
The python 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, 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 dish, the restaurant and the price.
- Create two lists: one for the prices and the other one for the restaurants. Add data, which correspond to 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), the program outputs a corresponding message. (Hint: you can use the list created at Step 4 for figuring out if the lines correspond to the entered dish).
- Write a function pricerange that takes the price list as an argument and returns the difference between the maximum and minimum prices.
- If the file contains any data about the entered dish, the program calls the function pricerange using the price list and outputs the result.
- Write a function maxprice that takes the price list and the restaurant list as its arguments and prints out the maximum price and the name of the restaurant which serves the most expensive dish the user queried.
Hint: First, find the maximum price from the list and then make a loop and find the position of the maximum price in the price list (the corresponding restaurant has the same position in the restaurants list).
9. Call the maxprice function after printing out the price range.
Go to Moodle and put your solution into Exercises 1.
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 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 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 other 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.