Table of contents
Chapter 1
Exercise 1.1: Printing in Python
Exercise 1.2: variables
Exercise 1.3: variables and types
Exercise 1.4: Changing variables
Exercise 1.5: Fix the error
Exercise 1.6: division
Exercise 1.7: Shopping
Exercise 1.8: Inches to centimeters
Exercise 1.9: Flat surface area
Chapter 2
Exercise 2.1: List slicing
Exercise 2.2: My List
Exercise 2.3: Simple statistics
Exercise 2.4: Oldest people in the world
Chapter 3
Exercise 3.1: While loop
Exercise 3.2: type of list elements
Chapter 1
Exercise 1.1: Printing in Python
Write a Python program that will produce this output:
This is my sentence
print("This is my sentence")
Exercise 1.2: variables
What is the final value of position
in the program below? (Try to predict the
value without running the program, then check your prediction.)
initial = "left"
position = initial
initial = "right"
left
initial = "left"
position = initial
initial = "right"
print(position)
Exercise 1.3: variables and types
What type of value is 4
? And 3.4
? How can you find out?
4
is an int
and 3.4
is a float
.
Use the type()
function for this.
print('4 is', type(4))
print('3.4 is', type(3.4))
Exercise 1.4: Changing variables
a) Write a Python program that will print the sentence "Hello world".
print("Hello world!")
b)
Now make a variable called age
which has a value of 4
age = 4
c)
Print the value of the age
variable. Write in a full sentence.
print("The age is", age)
d) Write the following as a comment in the program: "Now we will change the value of the variable age"
# Now we will change the value of the variable age
e)
Now put everything you have done in the previous subexercises all together into one cell. In addition, change the value of the variable age
to your own age. Finally, print a full sentence with the new value of the age
variable.
age = 4
# Now we will change the value of the variable age
age = 25
print("My age is", age)
Exercise 1.5: Fix the error
These exercises are about discovering errors in the code and rewriting the code to avoid them.
a) Rewrite this program so that it runs without any errors.
conc1 = 6
v1 = 10
v2 = 4
conc2 = (conc1*v1)/v2
print("The final concentration is: " + conc2)
conc1 = 6
v1 = 10
v2 = 4
conc2 = (conc1*v1)/v2
print("The final concentration is: " + str(conc2))
The final concentration is: 15.0
The technical explanation is that we can use addition only for the same type of variables or objects - this holds for numbers and strings. Because of that, we need to change our variable conc2
into string.
Exercise 1.6: division
Look at the following program, and try and predict what you think the value of c is. Check your answer by running the program in Python (but guess first!)
a = 1
b = 4
c = a / b * 3
print(c)
The program will print the number 0.75. The outcome, c, is a float because when we divide one integer by another integer we always get a float.
There are two operations in this program, a division and a multiplication. According to the order of operations, Python completes muliplications and divisions at the same time, with neither one taking an order of preference over the other. Thus, when there are both in one program, Python looks at the order the operations occur in the program. It therfore calculates a/ b first, and then multiplies the answer by 3. This gives us 0.75. If we had wanted Python to calculate b*3 first, we should put this operation inside parenthes.
Exercise 1.7: Shopping
This programme needs to calculate the total amount a customer needs to pay after shopping.
The goods that are available for shopping are bread, milk, cheese and yogurt.
The prices for different goods are: Bread: 20 kr Milk: 15 kr Cheese: 40 kr Yogurt: 12 kr.
The customer wants to buy 2 bread, 1 milk, 1 cheese and 3 yogurt. Make a programme that calculates how much this customer needs to pay in kr.
#the prices of different goods saved in given variables (in kr)
price_bread = 20
price_milk = 15
price_cheese = 40
price_yogurt = 12
#how many different goods the customer wants to buy
nr_of_bread = 2
nr_of_milk = 1
nr_of_cheese = 1
nr_of_yogurt = 3
#calculator for total amount in kr
total_amount = price_bread * nr_of_bread + price_milk * nr_of_milk + price_cheese * nr_of_cheese + price_yogurt * nr_of_yogurt
print("You need to pay:", total_amount, "kr")
Exercise 1.8: Inches to centimeters
a) Imperial units, such as inches and pounds, are commonly used in the USA outside of scientific work. \( 1cm = 0.394 inches \). Write a calculator program that prints the amount of centimeters in 1 inch, in a full sentence.
inch = 1 # the value of this variable can change depending on how many inches we want to convert to cm
cm = inch/0.394 # calculator which takes the value of inches and converts to cm
print("The amount of cm in", inch, "inches is", cm, "cm")
b) Now write a program that converts from cm to inches.
cm = 5 # the value of this variable can change depending on how many cm we want to convert to inches
inch = cm* 0.394
print("The amount of inches in", cm, "cm is", inch, "inches")
Exercise 1.9: Flat surface area
a)
Store the two dimensions of a flat surface in the variables width
and length
. Allow the width
to be 0.1m and the length
to be 0.5m. Caluclate the surface area using the formula width * length and print it along with the text "The surface area in m^2 is: ". Try manipulating the input values to see how the surface area changes.
width = 0.1 # defines a variable width as a value of 0.1
length = 0.5 # defines a variable length as a value of 0.5
surface = width * length # multiplies the two variables together and assigns to a new variable called surface
print("The surface area in m^2 is", surface) # prints the result in a full sentence
b) In molecular and cell biology the scale of meters is much too large to accurately describe events of interest. Instead, the unit of micrometers (or microns) is often used. A micrometer is one millionth of a meter, or simply \( 1*10^{-6} m \). Add a conversion step to your calculator that changes the final answer from meters to micrometers.
Don't forget that surface areas are given as squares(\( m^2 \)), which must be taken into account when converting between units. E.g \( 1m = 100cm \) but \( 1m^2 = 10000cm^2 \)
width = 0.1
length = 0.5
surface_in_meters = width * length
surface_in_microns = surface_in_meters*(10**12) # changes the calculated surface area from meters to micrometers
print("The surface area in m^2 is", surface_in_meters)
print("The surface area in microns^2 is", surface_in_microns)
Chapter 2
Exercise 2.1: List slicing
Here, you can test whether you are aware of different ways in which you can use []
and ()
.
Consider this code:
letters = ["a", "b", "c", "d"]
What is printed when following programs are run?
a)
print(letters)
You have used brackets to create a list. Printing the list will give all the elements whithin the list. Note that Python uses single quotation marks '
when strings.
['a', 'b', 'c', 'd']
b)
print(letters[1])
Writing brackets right after the name of the list that was created previously, is used to refer to one or several elements from the list. In this instance, we refer to an element from the list 'letters' that has index 1 (which is 2nd element in the list, with the 1st element having index 0).
b
c)
print(len(letters[1:3]))
Function len()
counts number of elements of a given string, list or array. For example, len("string")
, len([1, 2, 3])
, len(str_variable)
, len(mylist)
, etc.
In this case, you are given a list that is sliced. The new list, letters[1:3]
, includes elements from list letters
with indices 1, 2, but not 3. The number of elements in this newly sliced list will be printed, which is two.
2
Exercise 2.2: My List
a)
Create a list with the name my_list
that contains the numerical values [3, 132, 14]
.
my_list = [3, 142, 14]
b)
Use print()
to print out the first element in my_list to the screen (that is, element 0).
print(my_list[0])
c) Create a new list and decide the name for yourself. Let it be empty.
list2 = []
d)
Use append()
to add the string "hello" and "world!" to the last list.
list2.append("hello")
list2.append("world")
e) Use print to print out the list.
print(list2)
Exercise 2.3: Simple statistics
a) A group of students reported basic physical measurements. Use the following lists to store the information given:
height = [176, 169, 172, 172, 179, 160, 157, 170, 190, 154, 181, 185, 168, 184]
age = [34, 33, 27, 31, 19, 34, 22, 28, 23, 32, 20, 20, 24, 30, 21, 25]
weight = [62, 46, 56, 52, 80, 51, 84, 65, 92, 55, 53, 52, 84, 84, 61]
b) Quite often, data you receive from others will have problems, so you need to do some quality control fist.
Write a program that prints the length (number of items) of all the lists. If they do NOT all consist of the same amount of items, use the approriate method to delete the last element(s) of the lists that are too long. Then print their new lengths again to verify.
print(len(height))
print(len(age))
print(len(weight))
del age[-2:]
del weight[-1]
print(len(height))
print(len(age))
print(len(weight))
c) Write the sums of all the values in each list to separate variables.
Name your variables in a way that makes their origin easy to identify.
heightsum = sum(height)
agesum = sum(age)
weightsum = sum(weight)
d) Use the sums of the list indices to calculate the mean (average) height, age, and weight for this group of students. Round to one decimal point. Print out full sentences, not just values.
Different solutions are possible, rounding can also be done within the str
command, for example. Here is one solution:
mean_height = round(heightsum/len(height),1)
mean_age = round(agesum/len(age),1)
mean_weight = round(weightsum/len(weight),1)
print("Mean height of group: " + str(mean_height))
print("Mean age of group: " + str(mean_age))
print("Mean weight of group: " + str(mean_weight))
Exercise 2.4: Oldest people in the world
The data set used for this exercise is from the Wikipedia entry List of countries by life expectancy
. The table data was transformed into a CSV file called avg_age.csv
.
a)
Use pandas
to import the file and study the dataset by printing it out (in the Jupyter Notebook, simply writing the variable name gives a nicely formatted table)
import pandas
data = pandas.read_csv('avg_age.csv')
data
b) Make a list with the 'Both sexes life expectancy' column data, and one with the 'Country' column data. What is the highest average life expectancy for these countries?
avg = list(data['Both sexes life expectancy'])
country = list(data['Country'])
highest_exp = max(avg)
print("Highest average life expectancy for these countries is " + str(highest_exp))
c) How can you find out which country has this highest life expectancy?
You will need to find the index of the highest life expectancy entry first.
index_highest = avg.index(highest_exp)
print("The country with the highest average life expectancy is" + country[index_highest])
d) If you haven't done so, can you get to the answer to the question "What country has the highest life expectancy" with one command? Why would you (not) want to to it that way?
Make sure to balance your brackets!
print("The country with the highest average life expectancy is" + country[avg.index(max(avg))])
This is much less readable than using variables to store intermediate results.
Chapter 3
Exercise 3.1: While loop
a)
Write a program that takes a number as input from the user, and prints out all numbers from 0
up to, but not including, this number (hint: while...).
inp = input("Enter an integer:")
number = int(inp)
counter = 0
while counter < number:
print(counter)
counter += 1
b) Write a new program with a while-loop that takes a number as input from the user for each "round". Print this number in the while-loop. When the user enters a negative number, the program terminates.
number = 0
while number >= 0:
inp = input("Enter an integer:")
number = int(inp)
print(number)
print("You entered a negative number, the program terminates.")
Exercise 3.2: type of list elements
a) Given this list:
my_list = ['Hello', 'sqrt', 12, 1e9, ["A", "C", "G", "T"], -0.12, 3*"#"]
What are the variable types of the different elements of my_list
? Do not use any python to answer this question.
- string
- string
- int
- float
- list (!)
- float
- string
b) Now write a program using a 'while' loop that prints the type of each element to the screen. The output should look like this:
Element ____ is of type _____
Solution (code)
my_list = ['Hello', 'sqrt', 12, 1e9, ["A", "C", "G", "T"], -0.12, 3*"#"]
result = 0
while result < len(my_list):
print("Element", my_list[result], "is of type", type(my_list[result]))
result = result + 1
c)
You may now have seen that one of the elements is a list: ["A", "C", "G", "T"]
. Print out only that element from the list.
print(my_list[4])