In-class#

Coding Practice#

In today’s exercises, we will ask you to make assignments where you use some variables that you have defined earlier. This means that you need to write code which contains the name of a variable, not its value.

To give a simple example, after introducing a = 3, we might ask you to define an integer variable b with a value that is twice the value of a. Clearly, the value of b should be 6. However, writing b = 6 doesn’t fulfill the objective because you performed the computation yourself, and you should let the computer do the computation for you. Writing b = 2 * 3 is not a correct solution either, because you remembered the value of the variable a yourself, and you should let the computer store and retrieve values for you. To use the computer’s ability to store data and perform computation, you should solve the problem by writing b = 2 * a. Now, even if the value of a were a different integer, like 19084, the value of b would be twice the value of a.

Code 2.1: Josefine#

In this exercise, we use a name (Josefine) and a number (8) as an example.

Code 2.1a: Names and age#

Write a set of assignment statements where you assign the number 8 to the variable age and the name Josefine to the variable name. Print the values of age and name and verify that their values have been assigned correctly.

Code 2.1b: Names and values continued#

Print the data types of the variables age and name as well as their values. You should use one print statement for each variable and confirm they are as expected.

Hint: Look at Prep 2.2 and 2.3.

Code 2.1c: Small sentences#

Write a set of assignment statements where you define variables question and answer. The variable question should have the value "How old is Josefine?". The variable answer should have the value "Josefine is 8 years old.". You should use the variables age and name in your assignment statements. Print the variables question and answer and verify that they have been assigned correctly.

Hint: Look at the examples in exercise 2.5 of week 2 preparation.

Code 2.1d: Adult#

In Denmark, you are considered an adult when you are 18 years or older. Write an assignment where you define a boolean variable is_adult, which is equal to True if Josefine is grown up. Print the value of is_adult.

Code 2.2: Are you a student at DTU?#

Write a set of assignment statements where you assign a boolean variable is_student with the value True and a string variable student_campus with the value "Lyngby". Create a boolean variable is_dtu_student such that the variable is equal to True when the value of is_student is True and the value of student_campus is equal to "Lyngby".

Next, modify your code such that the variable is_dtu_student is equal to True when the value of is_student is True and the value of student_campus is equal to either "Lyngby" or "Ballerup". Experiment with different values of student_campus and verify that your implementation is correct.

Code 2.3: New record#

Create two floating-point variables, current_record with the value 5.21 and new_record_attempt with the value 5.42. Write a reassignment statement where you reassign the variable current_record to the maximum of current_record and new_record_attempt. Print the value of current_record after the reassignment and verify that the current record is now equal to the value of new_record_attempt.

Now set new_record_attempt to 5.35 and run the code. Did the current record update?

Code 2.4: Full rotations#

You are conducting an astronomy experiment to estimate how many times a planet has rotated around its axis. Based on your observations, the planet has rotated a total of 1740 degrees. Calculate and print how many full 360-degree rotations the planet has made. Calculate and print the remaining degrees after completing the full rotations.

Code 2.5: Predict execution#

Consider each of the following pieces of code. Without running the code, answer the questions:

  • Which variables exist after the code has been executed?

  • What are the values and the types of the variables?

  • What is printed to the console?

  • Did the code execute without errors?

Note your answers and discuss them with one of your fellow students. After discussing, run the code and compare the results with your predictions.

a = 15.5
b = a
a = 7
a = 5
b = 3
a = b
b = a
i = 15
i = 1 + 1
i = i + 1
letters = 'abc'
letters = 'x' + 2 * letters + 'y'
letters = 'x' + 2 * letters + 'y'

Code 2.6: Swap values#

Given two variables a and b, write down the steps you would take to swap their values. Verify your solution with Python. For example, start with this assignment.

a = 5
b = 3

Now, write the code which, after execution, will result is a having the value 3 and b having the value 5, but where you use the variables a and b in your code, not the values 3 and 5. You are free to use additional variables if needed.

Problem solving#

In the following exercises, you are asked to write code to solve some smaller and some bigger problems. Later in the course (starting from week 5), problem solving exercises will resemble the exercises you will see in the exam. For now, we may provide a few hints to guide you through the exercises. We encourage you to create an appropriately named .py file for each of the exercises below.

Problem 2.1: Volume of a sphere#

The volume of a three-dimensional sphere can be calculated as

\[V = \frac{4}{3} \pi r^{3}\]

where \(V\) is the volume of the sphere and \(r\) is the radius.

Write code that, defines a variable radius and assigns it a positive float of your choice. The code should calculate the volume of the sphere and print the result similar to the example below.

The volume of a sphere with radius 6 is 904.7786842338603

Make sure that your code works correctly - even if you change the value of radius.

Problem 2.2: Determining bacterial contamination#

In a set of experiments, you are cultivating a certain species of bacteria. You are concerned that some of your experiments may have been contaminated with other kinds of bacteria.

You know that all your experiments start with 500 million bacteria and that the bacterial population grows by anywhere between 600 million and 800 million per hour. If the average bacterial growth during the experiment is outside this range, you suspect that the experiment has been contaminated.

Write a piece of code that from, given the final number of bacteria in millions and the time each bacterial colony has been allowed to grow in hours, determines if the experiment has been contaminated and prints a message.

Consider an experiment where the final number of bacteria is 1738 million and the time is 2 hours. The bacteria population has increased by 1238 million, which is 619 million per hour. This growth is within the expected range, and the message should be as shown below.

Contaminated: False

Your code should start with the two lines where you define the variables final_population (in millions) and time (in hours). By changing these values, you should be able to test different experiments.

  • Experiment 1: final population 1738 million, time: 2 hours.

  • Experiment 2: final population 2872 million, time: 3 hours.

  • Experiment 3: final population 2367 million, time: 1 hour.

  • Experiment 4: final population 5062 million, time: 5 hours.

  • Experiment 5: final population 4228 million, time: 4 hours.

Problem 2.3: Health analysis#

You want to write code that prints a simple health analysis based on the age, weight, height, and sex of a person. The health analysis should include information regarding the body mass index (BMI), whether the BMI is in the normal range, and an estimate of the body fat percentage.

The BMI is calculated as

\[\mathrm{BMI}= \frac{{w}}{{h}^{2}}​\]

where \(w\) is the weight in kilograms and \(h\) is the height in meters. The BMI is in the normal range if it is greater than or equal to 18.5 and less than 25.

To estimate the percentage of body fat (PBF), you can use the Deurenberg formula

\[\mathrm{PBF} = 1.20\, \mathrm{BMI} + 0.23 y - 10.8 s - 5.4\]

where \(y\) is the person’s age in years and \(s\) is equal to \(0\) for women and \(1\) for men.

It is your task to write the code that starts with 4 lines defining the variables age, weight, height, and sex. The variable sex should be a string, either 'm' for male or 'f' for female. Using these variables, the code should calculate the BMI, check if it is in the normal range, and estimate the body fat percentage. The code should then print three messages. For example, if the person is 1.7 meters tall, weighs 60 kg, is 28 years old, and is female, the messages should be as shown below:

BMI is: 20.761245674740486
BMI is in normal range: True
PBF is: 25.953494809688586

It is important that your code works correctly if you change the values of the variables age, weight, height, and sex, but you can assume that the values are valid. Test your code with the values of a person who is 1.78 meters tall, weighs 92 kg, is 34 years old, and is male. Test your code with few other values as well.

Problem 2.4: Population modeling#

The number of individuals in a population over time can be modelled using an exponential function:

\[P = P_{0} \cdot e^{rt}\]

where \(P\) is the size of the population at time \(t\), \(P_{0}\) is the initial size of the population, \(r\) is the growth rate, and \(t\) is the time.

In this exercise, you are studying a population that starts with 1000 individuals and grows at a rate of 0.15 per year. You should write a code that calculates the time it takes for the population to reach a certain size. The code should then print this time in years and months.

For example, if the final population size is 4000, the time can be computed as

\[t = \frac{1}{r}\log\left({\frac{P}{P_0}}\right) = 9.2419 \text{ years}.\]

To express this in years and months, first compute the total number of months as rounded \(9.2419 \cdot 12\) months, which gives \(111\) months in total. Now, compute the number of years using integer division between total months and 12, this results in 9. Compute the remaining months by finding the reminder of the division between total months and 12, this results in 3.

The code should print the message as shown below:

Time to population of 4000 is 9 year(s) and 3 month(s).

Use your code to calculate the time it takes for the population to reach the size of 5000, 10000, 20000, 50000, and 100000 individuals.

Problem 2.5: Golf stroke analysis#

Apart from learning to code, you and your friends love to compete against each other on the local golf course. Now you want to use Python to analyze your performance.

Given the initial velocity \(v_0\) and the launch angle \(\theta\) of the ball, you can calculate the horizontal distance (range) \(R\) the ball will travel using the formula

\[R = \frac{v_{0}^{2} \sin(2 \theta)}{g}\]

where \(g = 9.821 \mathrm{ m/}\mathrm{s}^{2}\) is the acceleration due to gravity.

The time of flight \(T\) can be calculated as

\[T = \frac{2 v_{y}}{g}\]

where \(v_{y}\) is the vertical velocity component, which equals \(v_{0} \sin(\theta)\).

You should write a code that calculates the horizontal distance the ball will travel and the time of flight. The code should start with the two lines where you define the variables v0 in meters per second and theta in degrees. The code should then calculate the distance traveled and the time of flight and print the results. For printing, the range should be rounded up, and the time of flight should be rounded to two decimal points using the syntax round(T, 2).

For example, if the initial velocity is 20 m/s and the launch angle is 45 degrees, the message should be as shown below:

Range: 41 meters. Time of flight: 2.88 seconds.

Your friends noted the following statistics of their best shot from the last golf session:

  • Emma’s best shot: Initial velocity \(v_{0} = 28\) m/s, launch angle \(\theta = 46\) degrees.

  • Frederik’s best shot: Initial velocity \(v_{0} = 34\) m/s, launch angle \(\theta = 37\) degrees.

  • Josefine’s best shot: Initial velocity \(v_{0} = 31\) m/s, launch angle \(\theta = 61\) degrees.

By changing the values of v0 and theta in your code, answer the following questions: Which of your friends’ shots had the longest time of flight? Which of your friends’ shots covered the longest distance?

Problem 2.6: Normal range#

Your health analysis code was a success, and now you want to expand it with another feature. Given the height of a person, you want to display a message about the normal range of the weight. Recall that the BMI is in the normal range if it is greater than or equal to 18.5 and less than 25. Weight can be calculated as \(w=\mathrm{BMI}\cdot h^2\). By inserting the smallest and the largest normal BMI values, you can calculate the smallest and the largest normal weight values. When displaying the message, you should round the smaller value down and the larger value up.

For example, if the height is 1.7 meters, the message should be as follows:

For a height of 1.7 m, the normal weight range is between 53 and 73 kg.