Week 2: Variables and types

Week 2: In-Class#

Coding Practice#

A note on the demo task. Each Coding Practice session starts with the exercise that will be solved under live demo in the class. You should read through the exercises before demo and solve the Paper & Pen part of it. You don’t have to solve the coding part, but you are welcome to try and later compare your solution to the one presented in class.

Code 2.1: Arrival Times#

Given a scheduled arrival of a train (hours and minutes) and a delay in minutes, we need to determine the expected arrival time. You can assume that hours is a number between 0 and 23, minutes is a number between 0 and 59, and delay is a non-negative integer.

Pen & Paper

Consider a train that is scheduled to arrive at 21:30. That is, hours is 21 and minutes is 30.

  • What is the expected arrival time if the train is delayed by 17 minutes?

  • What is the expected arrival time if the train is delayed by 35 minutes?

  • Identify other special cases that the code needs to be able to handle?

Write down your results. Also write down all intermediate calculations. Can you identify a general approach that will work for all cases?

Code 2.2: Photo Grid#

Given a certain number of photos, we want to arrange them in a grid which is as close to square as possible. For example, if we have 16 photos, we can arrange them in a 4x4 square grid, but for 17 photos, we need a 5x5 square grid which leaves some cells empty.

Pen & Paper

Given a numbers of photos, you should determine two numbers: the size of the square grid (number of rows and columns)needed to fit all the photos, and the number of cells that will be left empty. Do the calculations for the following numbers of photos: 4 photos, 8 photos, 16 photos, 17 photos, and 240 photos.

Write down your results for each case. Also write down all intermediate calculations. Can you find a general method that works for any number of photos?

Code 2.3: Name and Age#

Josefine is 8 years old. Write two assignment statements. The first statement should assign Josefine’s age (in years) to the variable age and the second statement should assign Josefine’s name to the variable name. Write one print statement that prints the values of age and name and verify that their values have been assigned correctly.

Print the data types of the variables age and name as well as their values. You should use one print statement to print the value and type of age and the second print statement to print the variable and type of name. Confirm that variable types are as expected.

Hint: Look at Prep 2.3.

Code 2.4: Small Sentences#

Continue working with the variables age and name from the previous exercise. Using the variable name, define a variable question that contains a question How many days is Josefine old?. Using the variable age, define a variable answer that contains the answer Josefine is 2920 days old.. Here, you should assume that a year has 365 days.

Print the variables question and answer and verify that they have been assigned correctly. Now change the values of name and age to your own name and age. Print the variables question and answer again. Does your code still work correctly?

Hint: Look at the examples in Prep 2.7 from this weeks preparation exercises.

Code 2.5: Adult#

Continue working with the variable age from the previous exercises. 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, the value of which should be computed based on the value of age. The value of is_adult should be True if age is 18 or older, and False otherwise.

Code 2.6: Are You a Student at DTU?#

First, write two assignment statements where you make a boolean variable is_student with the value True and a string variable student_campus with the value "Lyngby". Now, write and assignment statement where you define a boolean variable is_dtu_student, the value of which should be computed based on the values of is_student and student_campus. The value of is_dtu_student should be True if 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.7: 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.8: 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.9: 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.10: 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 in 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.11: Sphere Volume#

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.12: 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 Python script 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.13: 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.14: 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.15: Golf Stroke#

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.16: 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.

Problem 2.17: Bed Fits #

You need to figure out whether a bed of size 0.9 times 2 meters will fit in the room of the size width times length. Write code that defines the variables width and length and assigns them positive float values. The code should then compute the boolean variable bed_fits which is True if the bed fits in the room and False otherwise. You need to consider that the bed can be placed in two different orientations.