In-Class#

Coding Practice#

Code 3.1: Simple temperature#

Write a piece of code that defines a numeric variable temperature and assigns it a value of your choice. Then write an if statement that prints It is freezing if the temperature is negative. Nothing should be printed if the temperature is zero or positive. Test your code with zero, positive, and negative values for temperature.

Code 3.2: Temperature continued#

Modify your code from the previous exercise by adding an else clause. The code should still print It is freezing for negative temperatures, but it should print It is not freezing for non-negative temperatures.

Code 3.3: Temperature continued#

Modify your code so that it prints:

  • It is freezing for temperatures below 0.

  • It is cold for temperatures between 0 (inclusive) and 15 (inclusive).

  • It is pleasant if the temperatures between 15 (exclusive) and 25 (inclusive).

  • It is hot for temperatures above 25.

You should achieve this behavior by adding elif clauses.

Test your code with different values of temperature to ensure it works for all cases. At a minimum, test with the values -10, 0, 10, 15, 20, 25, and 30.

Code 3.4: Christmas: Open presents#

Write code that starts by defining a string variable month and an integer variable day, for example:

month = "May"
day = 24

Write code that prints Let's open presents! if the month is December and the day is the 24th. Otherwise, the code should print No presents today :(. Test your code with different values of month and day including to 13th of December, 24th of December, 26th of December, 4th of May, and 24th of May.

Code 3.5: Christmas: Now with music#

Modify your code from the previous exercise such that it prints Can we listen to 'Last Christmas'? if the month is December. It should still print Let's open presents! on the 24th of December and No presents today :( otherwise. Thus, if the month is December, two messages should be printed: one regarding the music and one regarding the presents. Test your code with the same values of month and day as in the previous exercise.

Code 3.6: Christmas: No music on the 24th#

Modify your script from the previous exercise such that for the month of December, it only prints Can we listen to 'Last Christmas'? if the day is not the 24th. That is for all days in December two messages are printed, except on the 24th. Test your code with the same values of month and day as in the previous exercise.

Code 3.7: Fix buggy code#

You asked your friend to write some code for your project. The code is running without errors but is still producing incorrect behavior.

Identify what it’s supposed to do according to the comment above the code. Then, find any bugs and fix the code. Testing the code might help identify the bugs.

You are welcome to discuss this with others in your class.

x = 1
y = 2
z = 3

# Compute the largest of three numbers
if x > y and y > z:
    max_of_xyz = x
elif y > z and z > x:
    max_of_xyz = y
else:
    max_of_xyz = z
print(max_of_xyz)

The code below should print Weekend only if the day_of_week is equal to either "Saturday" or "Sunday". However, the code below is not correct. Can you fix it?

day_of_week = "Monday"
if day_of_week == "Saturday" or "Sunday":
    print("Weekend")
else:
    print("Work work.")

Code 3.8: Ordinal for digit#

Assume that the variable digit has a value that is a positive digit (i.e., a number 1, 2, 3, 4, 5, 6, 7, 8, or 9). Write a piece of code that stores the string with the ordinal number representation of digit in the variable ordinal. The value of ordinal should be either "1st", "2nd", "4th", "5th", "6th", "7th", "8th", or "9th". For example, if digit is 3, then ordinal should be "3rd".

Code 3.9: Special case#

Consider the following code:

number_of_experiments = 120 
number_of_successes = 30
probability_of_success = number_of_successes / number_of_experiments
print(probability_of_success)

If number_of_experiments has the value 0, the division on line 3 will raise a ZeroDivisionError. (Try it!)

Modify the code so that it checks for this case and computes probability_of_success only if number_of_experiments is different from 0. If number_of_experiments is 0, the code should print The probability of success is undefined, since the number of experiments is 0.

Problem Solving#

Problem 3.10: Body temperature#

Core body temperature is classified as:

  • Hypothermia: temperature less than or equal to 35 °C.

  • Normal: temperature greater than 35 °C and less than 37.5 °C.

  • Hyperthermia: temperature greater than or equal to 37.5 °C and less than 40 °C.

  • Hyperpyrexia: temperature greater than or equal to 40.0 °C.

Write a piece of code that defines a float variable temperature with a value of your choice, say 37.2. Then, based on the value of temperature, assign a string variable state that can take the values 'hypothermia', 'normal', 'hyperthermia', or 'hyperpyrexia'. Finally, use the print statement:

print("The temperature", temperature, "is", state)

to print the message, as shown below, where 37.2 is the value of temperature:

The temperature 37.2 is normal

Test your code with different values of temperature to make sure it works for all cases. At least, test with values 34.9 (the state should be hypothermia), 35 (also hypothermia), 36.2 (normal), 37.5 (hyperthermia), 37.9 (hyperthermia), 40.0 (hyperpyrexia), and 40.1 (hyperpyrexia). You don’t need to check whether the temperature is physically possible.

Problem 3.11: Nitrate levels#

Nitrate levels in drinking water are categorized as:

  • Very low: Nitrate levels less than or equal to 4.0 mg/l.

  • Low: Nitrate levels above 4.0 but less than or equal to 9.0 mg/l.

  • Normal: Nitrate levels above 9.0 and below 40.0 mg/l.

  • High: Nitrate levels greater than or equal to 40.0 but below 50.0 mg/l.

  • Very high: Nitrate levels greater than or equal to 50.0 mg/l.

Note that when the nitrate level falls on the border between two categories, it is included in the category further from normal. For example, a nitrate level of 4.0 mg/l is considered very low, and a nitrate level of 40.0 mg/l is considered high.

Write a piece of code that defines a float variable nitrate_level with a value of your choice, say 12.3. Based on the value of nitrate_level, assign a string variable category that can take the values 'very low', 'low', 'normal', 'high', or 'very high'. Finally, use the print statement:

print("The nitrate level", nitrate_level, "mg/l is", category)

to print the message as shown below, where 12.3 is the value of nitrate_level:

The nitrate level 12.3 mg/l is normal

Test your code with different values of nitrate_level to ensure it works for all cases. At least, test with values 3.5 (very low), 4.0 (very low), 5.9 (low), 9.0 (low), 12.8 (normal), 40.0 (high), 45 (high), and 50 (very high).

Problem 3.12: Valid class#

Schoolchildren are divided into classes. The class is valid if the total number of children is not less than 20 and not greater than 30. Furthermore, there should be a balance between the number of girls and the number of boys in the class. For the class to be valid, the difference between the sizes of these two groups should not be greater than 5.

Write a piece of code that defines two integer variables number_girls and number_boys. Then, based on the values of these variables, assign a boolean variable is_valid, which is True if the class is valid and False otherwise.

Finally, use the print statement:

print("Class with", number_girls, "girls and", number_boys, "boys is valid:", is_valid)

to print the message as shown below, where number_girls is 18 and number_boys is 11:

Class with 18 girls and 11 boys is valid: False

Test your code with different values to ensure it works as expected. You don’t need to check whether the number of children is positive.

A good way to test the code is to create a table with different values of number_girls and number_boys, along with the expected value of is_valid. For example, the table below shows the expected values for some cases. Make sure your code gives the expected value for all cases in the table.

number_girls

number_boys

expected value of is_valid

comment

15

15

True

all fine

15

16

False

class too large

10

9

False

class too small

12

8

True

all fine

13

8

True

all fine

9

15

False

too many boys

109

5

False

multiple conditions unmet

1

15

False

multiple conditions unmet

Problem 3.13: Risk of heart attack#

Write a piece of code that determines the risk of a person having a heart attack based on the following decision tree:

image

Your code should first define three variables: age (an integer), weight (an integer), and variable is_smoker (a boolean). For example:

age = 45
weight = 80
is_smoker = False

Then, the code should assign a boolean variable high_risk which is True if the risk is high according to the decision tree, and False if the risk is low.

Use a print statement:

print("Age", age, "weight", weight, "smoker", is_smoker, "high risk", high_risk)

to test your code.

Test your code with different values of age, weight, and is_smoker to ensure it works for all cases. At least, try the values from the following table:

age

weight

is_smoker

expected value of high_risk

8

40

False

False

17

62

True

True

18

61

False

False

23

65

True

False

38

120

True

True

64

70

False

False

Problem 3.14: Triangle type#

Given three numbers, you want to determine whether they are valid side lengths of a triangle and what type of triangle they form. For this, consider the following image.

image

Write a piece of code that defines three float variables a, b, and c, representing the lengths of the sides of a triangle. Based on these numbers, the code should assign a string variable triangle_type which should take one of the following values:

  • "Invalid lengths" if any of the side lengths is zero or negative.

  • "Not a triangle" if the side lengths cannot form a triangle.

  • "Scalene" if all side lengths are different.

  • "Isosceles" if two side lengths are equal and the third one is different.

  • "Equilateral" if all side lengths are equal.

To check whether the side lengths can form a triangle, use the triangle inequality, which states that the sum of the lengths of any two sides must be greater than the length of the remaining side. The inequality must hold for all combinations of two sides.

Test your code with different values of a, b, and c to ensure it works for all cases.

Problem 3.15: Stock status#

When customers visit a webshop page for a certain product, they see information about the stock status. This information is based on two integers: number_of_items (the number of items currently in stock) and days_to_delivery (the number of days until delivery of new items from the factory, where 0 indicates that new items are not expected).

The stock status displayed to the customer is:

  • In stock when there are 6 or more items in stock.

  • Only <n> left in stock when there are between 1 and 5 items in stock. Here, <n> is the number of items in stock.

  • Available in <d> days when there are no items in stock but new items are expected. Here, <d> is the number of days to delivery.

  • Out of stock when there are no items in stock and no new delivery is expected.

  • Unknown when either number of items is negative, or there are no items in stock and the number of days to delivery is negative.

Another way of representing the stock status is with a decision tree:

image

Write a piece of code that defines two integer variables number_of_items and days_to_delivery. Based on the values of these two variables, the code should assign a string variable stock_status with the values described above.

Use the print statement:

print(number_of_items, "items", days_to_delivery, "days:", stock_status)

to test your code.

Test your code with different values of number_of_items and days_to_delivery to make sure it works for all cases. At least, test with the values from the following table:

number_of_items

days_to_delivery

expected value of stock_status

16

0

In stock

6

0

In stock

5

0

Only 5 left in stock

1

0

Only 1 left in stock

0

3

Available in 3 days

0

0

Out of stock

0

-2

Unknown

-1

0

Unknown

-1

8

Unknown

Problem 3.16: Can you drive a car?#

In Denmark, you are allowed to drive a car if you are at least 18 years old, have a valid driver’s license, and have a blood alcohol content below 0.5 per mille. Additionally, you may drive a car if you are 17 years old, have a valid driver’s license, have a blood alcohol content below 0.5 per mille, and have a companion in the car.

You should write code that, based on the integer variable age, boolean variable has_license, float variable BAC (blood alcohol content, in per mille), and boolean variable has_companion, determines whether you are allowed to drive a car, and stores the result in the boolean variable can_drive.

Problem 3.17: Which pond animal?#

You are near a pond, and you hear an animal; however you cannot see it. Your programmer friend, who only speaks in booleans and doesn’t know many animals, will help you identify the animal. He tells you the following information:

  • The variable looks_like_beaver stores whether the animal looks like a beaver.

  • The variable has_beak stores whether the animal has a beak.

Using this information, you should assign the variable animal to take the string value "duck", "platypus", "beaver", or "fish". As visual guidance, consider the Venn diagram below.

image