ICS3U Computer Science • Ontario Grade 11

Corrected exercises: variables, data types and expressions (ICS3U)

Exercises: variables, data types and expressions (ICS3U)

Name: Class: Date:

Solutions

Suggested time: 2 h 30 · No calculator · 12 exercises
https://www.letuteurscientifique.ca/en/exercices/ics3u-variables-data-types-expressions

These ten corrected exercises, preceded by two lists of direct calculations, cover the first chapter of ICS3U, Introduction to Computer Science, Grade 11, University Preparation, in Ontario: constants and variables, the data types integer, floating point, string and Boolean value, assignment statements with arithmetic and string expressions, the arithmetic operators and the order of operations, and programs that take user input, process it and display a result, organized by the input-process-output model.

What the set covers, the traps it targets

The code is in Python 3; traces, types and the order of operations are reasoned the same way in any language, and a line of the solutions says where Java gives another result.

Exercise 0.1 evaluates ten expressions and exercise 0.2 names the type of ten values. By the end, you can trace a sequence of assignments in a table (exercise 1), predict what print shows when brackets, ** and / are mixed (exercise 2), choose the type of each variable from what the program does with it (exercise 3), explain why two numbers typed by the user come out joined instead of added, and fix it (exercise 4), and fill the IPO chart of a program that uses constants (exercise 5). Part B gives an exchange of two values that loses one of them, at a weather station (exercise 6), a runner's pace calculator with three bugs to correct (exercise 7), five statements to correct (exercise 8), a recipe scaled with // instead of / (exercise 9), and a time-lapse camera program to write from its statement (exercise 10).

The thread of the set: a variable is a named box that holds one value of one type; = computes the right side first, with the values and the types the boxes hold at that moment, then puts the result in the box on the left. Five traps are named in the solutions: (1) reading = as an equation, exercises 1 and 8; (2) forgetting that input() returns a string, so 12 and 30 make 1230, exercises 0.2, 4 and 7; (3) expecting an int from /, which always gives a float, exercises 0.1, 0.2, 3, 8, 9 and 10; (4) the order of operations, with -a ** 2 read as (-a) ** 2, ** grouped from the left or brackets misplaced, exercises 0.1, 2, 7 and 8; (5) exchanging two variables without a temporary variable, which overwrites one value, exercise 6.

A calculator is allowed for the arithmetic, but every trace and every type is worked out by hand, as on a unit test.

  • 12 corrected exercises • 120 points • 150 minutes
  • Self-checking, 103 answers
  • No calculator
Start exercise 0.1 The chapter sheet
Print

Print the homework or the solutions

The homework without solutions, one exercise per page, and the solutions on their own: it comes with your free space. An email is enough, no password, and you come back here.

Create my free space

Already have one? Sign in

Course recap

  • • = is the assignment operator: the right side is computed first, with the current values, then stored in the variable on the left. x = x + 1 adds 1 to x.
  • • A variable holds a value, not a formula: changing score later does not recompute a variable computed from it.
  • • Four types: int (42), float (42.0), str ('42'), bool (True, False). Quotes make a str; one float in an operation makes the result a float.
  • • / always gives a float on int and float values (12 / 4 is 3.0); // gives the whole quotient and % the remainder (23 // 5 is 4, 23 % 5 is 3).
  • • Order of operations: brackets, then ** (from right to left, before a minus sign in front), then * / // % from left to right, then + - from left to right.
  • • input() always returns a str: int(input()) or float(input()) to compute. + between two str joins them.
  • • A constant is written in capital letters (LATE_FEE) and defined once, at the top of the program.
  • • Exchange two variables with a temporary variable: temp = a, a = b, b = temp.

Calculations: expressions to evaluate

Exercise 0.1: Order of operations: ten expressions to evaluate

10 answers to check

Give the value Python computes for each expression. A result that print shows with a decimal point, such as 18.0, is a float: type its value in the field, 18.

Method: brackets first; then **, grouped from right to left and applied before a minus sign written in front; then *, /, // and %, from left to right; then + and -, from left to right. The operator / always gives a float. Here // (integer division) and % (remainder) are used on positive whole numbers only.

  • a) 6 + 4 * 3
  • b) (6 + 4) * 3
  • c) 20 - 8 / 4
  • d) 2 ** 2 ** 3
  • e) -5 ** 2
  • f) (-5) ** 2
  • g) 9 / 4
  • h) 23 // 5
  • i) 23 % 5
  • j) 10 - 2 * 3 ** 2 / 6

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
f)
g)
h)
i)
j)
Show the solution

Answers

  • a) 18
  • b) 30
  • c) 18.0, a float
  • d) 256
  • e) -25
  • f) 25
  • g) 2.25
  • h) 4
  • i) 3
  • j) 7.0, a float

The same reading on every line: find the operator that runs first, compute it, rewrite the shorter expression, and start again.

a)

* before +: 4 * 3 = 12, then 6 + 12 = 18, an int.

b)

The brackets first: 6 + 4 = 10, then 10 * 3 = 30.

c)

/ before -: 8 / 4 = 2.0, a float, then 20 - 2.0 = 18.0.

One float in the expression makes the result a float: the value is 18, print shows 18.0.

d)

** is grouped from right to left: 2 ** 2 ** 3 is 2 ** (2 ** 3) = 2 ** 8 = 256.

Pitfall: (2 ** 2) ** 3 = 4 ** 3 = 64, the left-to-right reading.

e)

** runs before the minus sign written in front: -5 ** 2 is -(5 ** 2) = -25.

Pitfall: 25, which is the value of (-5) ** 2.

f)

The brackets make -5 the base: (-5) ** 2 = (-5) × (-5) = 25.

g)

9 / 4 = 2.25: / is true division, even between two int.

In Java, 9 / 4 between two int gives 2, the decimals dropped; Python writes that operation 9 // 4.

h)

23 // 5 counts the whole 5s in 23: 5 × 4 = 20 is at most 23, and 5 × 5 = 25 is more, so 4.

i)

23 % 5 is what is left over: 23 - 20 = 3.

Check: 5 × 4 + 3 = 23.

j)

** first: 3 ** 2 = 9. Then * and / from left to right: 2 * 9 = 18, then 18 / 6 = 3.0. Then 10 - 3.0 = 7.0.

Tick the exercises you have done or want to review: a free account, no password, keeps your ticks and your right answers from one visit to the next, tells you which chapter to tackle next and lets you ask for the exercise you are missing. Create your space, an email is enough.

Calculations: types to name

Exercise 0.2: Data types: the type of ten values

10 answers to check

For each value or expression, give its type in Python: int (integer), float (floating point number), str (string) or bool (Boolean value).

Method: quotation marks make a str, whatever is inside them; True and False without quotes are the two bool values; a number written with a decimal point is a float; an operation gives a float as soon as one operand is a float, and / always gives a float.

  • a) 42
  • b) 42.0
  • c) '42'
  • d) False
  • e) 'False'
  • f) 12 / 4
  • g) 12 // 4
  • h) 5 * 2.0
  • i) '12' + '30'
  • j) The value that input() returns when the user types 25.

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
f)
g)
h)
i)
j)
Show the solution

Answers

  • a) int
  • b) float
  • c) str
  • d) bool
  • e) str
  • f) float, 3.0
  • g) int, 3
  • h) float, 10.0
  • i) str, '1230'
  • j) str, '25'
a)

A whole number without a decimal point: int.

b) The decimal point makes it a float, even with 0 after it.

c) The quotes make it text: '42' is a str of two characters, 4 and 2.

d)

False without quotes is one of the two Boolean values: bool.

e) With quotes, 'False' is a str of five letters; it is not a Boolean value.

f)

/ always gives a float: 12 / 4 = 3.0.

g) // between two int gives an int: 12 // 4 = 3.

h)

One operand is a float, 2.0, so the product is a float: 10.0.

i)

+ between two str joins them end to end, which is called concatenation: '12' + '30' = '1230', a str. No addition takes place.

j)

input() returns what was typed as a str, '25', even when it looks like a number.

Pitfall: answering int. The conversion happens when the program calls int() or float(), on the same line or later.

Part A: the basics (/50)

Exercise 1: Assignment is not equality: tracing six lines

7 answers to check

In a program, = is the assignment operator: Python computes the expression on its right with the values the variables hold at that moment, then stores the result in the variable on its left. A trace table follows this by hand: one column per variable, one row per line, and a value is written only on the line that changes it.

Python
score = 4               # line 1
bonus = score * 3       # line 2
score = score + bonus   # line 3
bonus = bonus - score   # line 4
score = score * 2       # line 5
print(score, bonus)     # line 6
  • a) Draw the trace table of the program. Give the value of score after line 3 and the value of bonus after line 4.
  • b) What does line 6 print? Give the two numbers in the order they appear.
  • c) In algebra, the equation score = score + bonus forces bonus to be 0. What does line 3 do in Python?
  • d) Line 3 changes score, and bonus was computed from score on line 2. What does bonus hold just after line 3?
  • e) A student rewrites line 5 as score * 2 = score. What happens?

Type your answers, the page tells you right or wrong 0/7

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) score = 16 after line 3; bonus = -4 after line 4
  • b) 32 -4
  • c) It computes 4 + 12 = 16, then stores 16 in score
  • d) 12: line 3 does not recompute bonus
  • e) A SyntaxError: the program does not start

The method: before writing a row, compute the right side with the values in the rows above, then write the result in the column of the variable on the left. Nothing else changes.

a)

Line 1: score = 4.

Line 2: bonus = 4 * 3 = 12.

Line 3: score = 4 + 12 = 16.

Line 4: bonus = 12 - 16 = -4.

Line 5: score = 16 * 2 = 32.

After line 3, score holds 16; after line 4, bonus holds -4.

Pitfall: computing line 4 with the old score, 12 - 4 = 8. Line 3 has already replaced 4 by 16.

b)

Line 6 prints the last values of the table: 32 -4.

print with two values separated by a comma shows them on one line, with one space between them.

c)

Line 3 is an instruction, not an equation: compute score + bonus = 4 + 12 = 16, then put 16 in score. The old value 4 is lost.

A test of equality is written == and belongs to the next chapter; score == score + bonus would be False here.

d)

bonus still holds 12. Line 2 stored the value 12, computed once; it did not store the formula score * 3.

= copies a value at one moment; it does not link two variables.

e)

Python refuses the line before running anything: a SyntaxError, because score * 2 is an expression, and an expression cannot receive a value.

The variable that receives the value is on the left: score = score * 2.

LinescorebonusOutput142123164-4532632 -4Trace table

Exercise 2: Order of operations: predicting what print shows

9 answers to check

Python follows the order of operations of mathematics, with three rules of its own: ** is grouped from right to left, ** runs before a minus sign written in front, and / always gives a float.

Python
a = 4
b = 3
print(a + b * 2)        # line 3
print((a + b) * 2)      # line 4
print(-a ** 2)          # line 5
print(2 ** b ** 2)      # line 6
print(a * b / 8 + 1)    # line 7
print(a - b - 1)        # line 8
  • a) What do lines 3 and 4 print?
  • b) What does line 5 print? Which brackets does Python put in -a ** 2?
  • c) What does line 6 print? What would (2 ** b) ** 2 give?
  • d) What does line 7 print?
  • e) What does line 8 print? What would a - (b - 1) give?

Type your answers, the page tells you right or wrong 0/9

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) Line 3: 10; line 4: 14
  • b) -16, read as -(a ** 2)
  • c) 512; (2 ** b) ** 2 gives 64
  • d) 2.5
  • e) 0; a - (b - 1) gives 2

Replace each variable by its value, a = 4 and b = 3, then apply the ranks of the table below, from first to last.

a)

Line 3: * before +, b * 2 = 6, then 4 + 6 = 10.

Line 4: the brackets first, 4 + 3 = 7, then 7 * 2 = 14.

b)

** runs before the minus sign in front: -a ** 2 is -(a ** 2) = -(16) = -16.

Pitfall: 16, the value of (-a) ** 2. To square -4, the brackets are needed.

c)

** from right to left: 2 ** b ** 2 is 2 ** (3 ** 2) = 2 ** 9 = 512.

Read from left to right, (2 ** 3) ** 2 = 8 ** 2 = 64.

Java has no ** operator: it writes Math.pow(2, 9), which gives the double 512.0.

d)

* and / have the same rank, so from left to right: a * b = 12, then 12 / 8 = 1.5, then 1.5 + 1 = 2.5.

In Java, 4 * 3 / 8 between int gives 1, and the line prints 2.

e)

The two - have the same rank, so from left to right: (4 - 3) - 1 = 0.

With brackets on the right, a - (b - 1) = 4 - 2 = 2: the grouping of a subtraction changes its result.

RankOperatorsGrouping1( )innermost first2**right to left3- written in frontafter **4* / // %left to right5+ -left to rightPython's order of operations, first to last

Exercise 3: Choosing the data type of each variable

9 answers to check

A public library is writing a program to manage its loans. Before writing a line of code, the programmer chooses a type for each piece of data: int for a count, float for a measure or an amount with decimals, str for text, bool for an answer that is yes or no.

  • a) Choose the type of each piece of data. The number of books a member has borrowed. The late fee per day, 0.25 dollar. The member's name. Whether the member's card is valid. The card number, printed on the card as 0045812.
  • b) The program runs days_late = 6, then fee = days_late * 0.25, then print(fee). What is printed?
  • c) Another part runs per_shelf = 18 / 6, then print(per_shelf). What is printed?
  • d) A programmer stores the card number as a number: card = int('0045812'), then print(card). What is printed?
  • e) The fee 0.25 appears in four formulas of the program. The programmer replaces it by a constant defined once at the top. Which name follows the naming convention for a constant?

Type your answers, the page tells you right or wrong 0/9

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) int; float; str; bool; str
  • b) 1.5
  • c) 3.0
  • d) 45812: the two leading zeros are lost
  • e) LATE_FEE
a)

The number of books is a count: int.

The fee per day has decimals: float.

The name is text: str.

Valid or not is a yes-or-no answer: bool, True or False.

The card number is made of digits, but nobody adds or multiplies two card numbers, and its leading zeros are part of it: str. The same goes for a phone number or a postal code.

Pitfall: choosing int because the data is made of digits. The type follows what the program does with the data.

b)

fee = 6 * 0.25 = 1.5. One operand is a float, so fee is a float, and print shows 1.5.

c)

/ always gives a float: 18 / 6 = 3.0, and print shows 3.0, not 3.

In Java, 18 / 6 between two int gives 3, and 19 / 6 gives 3 as well; in Python, 19 / 6 gives 3.1666666666666665.

d)

int('0045812') reads the digits as a number, 45812: an int has no leading zeros, so print shows 45812.

Stored as the str '0045812', the card number keeps its seven characters.

e)

LATE_FEE: a constant is written in capital letters, words separated by underscores.

late_fee is the style of an ordinary variable; LateFee is the style of a class name, a notion of the Grade 12 course (ICS4U).

With the constant, a new fee changes one line instead of four, and no formula is forgotten.

Exercise 4: input() returns a string: 12 and 30 make 1230

6 answers to check

The program below asks the user for two numbers and is meant to display their sum.

Python
first = input('First number: ')
second = input('Second number: ')
total = first + second
print('Total:', total)
  • a) The user types 12, then 30. What does the last line display?
  • b) What is the type of first after line 1?
  • c) The user now types 30, then 12. What is displayed?
  • d) Which version of line 1 corrects the program, line 2 being corrected the same way?
  • e) After the correction, what is displayed for 12 and 30? What would be displayed if float replaced int on both lines?

Type your answers, the page tells you right or wrong 0/6

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) Total: 1230
  • b) str
  • c) Total: 3012
  • d) first = int(input('First number: '))
  • e) Total: 42; with float, Total: 42.0
a)

input() returns the characters typed: first = '12' and second = '30'.

+ between two str is concatenation: '12' + '30' = '1230'. The program displays Total: 1230, with no error message.

b)

str, the type of every value input() returns, whatever the user types.

c)

Concatenation keeps the order: '30' + '12' = '3012', so Total: 3012.

Two orders, two results: + on strings is not an addition.

d)

first = int(input('First number: ')): input() reads the str '12', then int() turns it into the int 12.

input(int('First number: ')) tries to convert the prompt itself and stops with a ValueError; int('First number: ') converts the prompt without ever reading the keyboard, and stops the same way.

In Java, Scanner's nextLine() also returns a String, and + also joins two String; nextInt() reads an int directly.

e)

With int: 12 + 30 = 42, and the program displays Total: 42.

With float, the two values are 12.0 and 30.0, and the program displays Total: 42.0.

float(input()) accepts a decimal such as 2.5 as well; the choice follows the data, as in exercise 3.

As written: three strfirst'12'second'30'total'1230'With int(input()): three intfirst12second30total42

Exercise 5: Input, processing, output: a 3D printing quote

10 answers to check

A school maker space charges each 3D print 0.05 dollar per gram of filament, plus 1.20 dollars per hour of printer time. The student types the mass of the print in grams and the printing time in minutes, and the program displays the cost.

The input-process-output model (IPO) splits a program into three columns: what the user gives, what the program computes, what it displays.

Python
PRICE_PER_GRAM = 0.05   # dollars per gram
MACHINE_RATE = 1.20     # dollars per hour
mass = float(input('Mass of filament (g): '))
minutes = float(input('Printing time (min): '))
hours = minutes / 60
cost = mass * PRICE_PER_GRAM + hours * MACHINE_RATE
print('Cost:', round(cost, 2), 'dollars')
  • a) Place each item in the IPO chart: the mass typed, the time typed, the line hours = minutes / 60, the cost on the screen.
  • b) The price per gram, 0.05, is not typed by the user. Is it an input of the program?
  • c) A student types 84 and 150. Give the value of hours and the cost displayed.
  • d) A student moves the line hours = minutes / 60 below the line that computes cost. What happens?
  • e) The maker space raises its price to 0.06 dollar per gram. How many lines of the program change, and what is the new cost for 84 g and 150 min?

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) Input: the mass, the time; processing: hours = minutes / 60; output: the cost
  • b) No: a constant written in the program
  • c) hours = 2.5; Cost: 7.2 dollars
  • d) A NameError: hours does not exist yet when cost is computed
  • e) 1 line, PRICE_PER_GRAM = 0.06; 8.04 dollars
a)

Input: the mass and the time, typed by the user.

Processing: hours = minutes / 60, then the cost formula; nothing appears on the screen.

Output: the cost, displayed by the last line.

b)

No. An input comes from the user while the program runs. 0.05 and 1.20 are fixed data, written once in the program as the constants PRICE_PER_GRAM and MACHINE_RATE; in the IPO chart, they belong to the processing.

c)

hours = 150 / 60 = 2.5.

cost = 84 × 0.05 + 2.5 × 1.20 = 4.2 + 3.0 = 7.2.

round(cost, 2) keeps at most two decimals, so the program displays Cost: 7.2 dollars. Showing 7.20 is a question of string formatting, which comes with strings.

d)

Python runs the lines in order, from top to bottom. When the cost line runs, hours has never received a value: the program stops with a NameError, name 'hours' is not defined.

Pitfall: thinking that Python finds the definition further down. A program is a sequence, and a variable exists only once a line has assigned it.

e)

1 line changes: PRICE_PER_GRAM = 0.06. The formula reads the constant and does not change.

cost = 84 × 0.06 + 2.5 × 1.20 = 5.04 + 3.0 = 8.04 dollars.

InputProcessingOutputmass (g), typedhours = minutes / 60cost (dollars)time (min), typedcost = mass × 0.05 + hours × 1.20on the screenconstants 0.05 and 1.20IPO chart of the 3D printing quote

Part B: problems and reasoning (/50)

Exercise 6: Problem: the weather station whose sensors were swapped

8 answers to check

A weather station reads two temperature sensors. The technician plugged them in reverse: the program receives the outdoor temperature as its first input and the indoor temperature as its second. A programmer adds lines 3 and 4 to put each value back in the right variable.

Python
indoor = float(input('Indoor sensor: '))       # line 1
outdoor = float(input('Outdoor sensor: '))     # line 2
indoor = outdoor                                # line 3
outdoor = indoor                                # line 4
print('Indoor:', indoor, 'Outdoor:', outdoor)   # line 5
  • a) The sensors send -6.5, then 21.0. Trace the program: which values does line 5 display for indoor and for outdoor?
  • b) Which reading is lost, and on which line does the program lose it?
  • c) Which three lines, put in place of lines 3 and 4, exchange the two values?
  • d) Trace the corrected program on the same readings: what is displayed?
  • e) Python also accepts the single line indoor, outdoor = outdoor, indoor. Why does it not lose a value?

Type your answers, the page tells you right or wrong 0/8

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) Indoor: 21.0 Outdoor: 21.0
  • b) -6.5, lost on line 3
  • c) temp = indoor, then indoor = outdoor, then outdoor = temp
  • d) Indoor: 21.0 Outdoor: -6.5
  • e) The right side is evaluated completely before either variable changes
a)

Line 1: indoor = -6.5 (the outdoor reading). Line 2: outdoor = 21.0.

Line 3: indoor = outdoor, so indoor = 21.0.

Line 4: outdoor = indoor, and indoor now holds 21.0, so outdoor = 21.0.

Line 5 displays Indoor: 21.0 Outdoor: 21.0.

b)

The reading -6.5 is lost on line 3: indoor receives 21.0, and no variable holds -6.5 any more. Line 4 can only copy a value that still exists.

Pitfall: reading lines 3 and 4 as one simultaneous exchange. They run one after the other, and the first one overwrites a value.

c)

A third variable keeps the value that line 3 would overwrite:

temp = indoor, then indoor = outdoor, then outdoor = temp.

The order temp = indoor, outdoor = temp, indoor = outdoor gives -6.5 to both; the order temp = outdoor, outdoor = indoor, indoor = outdoor also gives -6.5 to both. A trace of three rows settles it.

d)

temp = -6.5, then indoor = 21.0, then outdoor = temp = -6.5.

The program displays Indoor: 21.0 Outdoor: -6.5: each reading is back in its variable, and both readings still exist.

e)

Python computes the whole right side first, the pair of values (21.0, -6.5), then assigns them, the first to indoor and the second to outdoor. No variable is changed while the right side is read.

Java has no such line: an exchange there is written with a temporary variable, as in c).

Lineindooroutdoor1-6.5221.0321.0421.0As writtenLineindooroutdoortemp1-6.5221.03-6.5421.05-6.5With temp

Exercise 7: Problem: correcting a runner's pace calculator

7 answers to check

A runner types the distance of a run in kilometres, then its time in minutes and seconds. The program must display the pace, in minutes per kilometre, and the average speed, in kilometres per hour. Test data: 5 km in 27 min 30 s.

Python
distance = input('Distance (km): ')            # line 1
minutes = int(input('Minutes: '))              # line 2
seconds = int(input('Seconds: '))              # line 3
total_min = (minutes + seconds) / 60           # line 4
pace = total_min / distance                    # line 5
speed = distance / total_min / 60              # line 6
print('Pace:', pace, 'min/km')                 # line 7
print('Speed:', speed, 'km/h')                 # line 8
  • a) The runner types 5, 27 and 30. What happens when the program runs as written?
  • b) Line 1 is corrected to distance = float(input('Distance (km): ')). What does total_min hold now, and what pace does line 7 display?
  • c) Correct line 4. What must total_min hold for 27 min 30 s?
  • d) With lines 1 and 4 corrected, what pace is displayed? Write it in minutes and seconds per kilometre.
  • e) Correct line 6, and give the speed to the hundredth.

Type your answers, the page tells you right or wrong 0/7

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) It stops on line 5 with a TypeError: distance is a str
  • b) total_min = 0.95; Pace: 0.19 min/km
  • c) total_min = minutes + seconds / 60 = 27.5
  • d) 5.5 min/km, that is 5 min 30 s per kilometre
  • e) speed = distance / total_min * 60, about 10.91 km/h

Each bug is found by comparing what the program computes with a result worked out by hand on the test data. The corrected program is below.

a)

Line 1 leaves distance as the str '5'. Lines 2 to 4 run, then line 5 divides a float by a str: the program stops with a TypeError, unsupported operand type(s) for /.

Nothing is displayed: the error comes before line 7.

b)

Line 4 adds 27 minutes and 30 seconds as if they were the same unit: (27 + 30) / 60 = 57 / 60 = 0.95.

pace = 0.95 / 5.0 = 0.19, and line 7 displays Pace: 0.19 min/km.

A pace of 0.19 min/km is about 11 seconds per kilometre: the size of the answer shows the bug, even without an error message.

c)

Only the seconds are converted: 30 s = 30 / 60 = 0.5 min. Line 4 becomes total_min = minutes + seconds / 60, and the order of operations divides before it adds.

total_min = 27 + 0.5 = 27.5.

Pitfall: the brackets of the original line force the addition first, which mixes minutes and seconds.

d)

pace = 27.5 / 5.0 = 5.5 min/km.

0.5 min = 30 s, so the pace is 5 min 30 s per kilometre.

e)

Line 6 as written divides by 60 a second time: 5.0 / 27.5 / 60 is about 0.003, a speed in kilometres per minute divided again by 60.

The runner covers 5.0 / 27.5 kilometres per minute, and an hour has 60 minutes: speed = distance / total_min * 60.

speed = 5.0 / 27.5 × 60 = 10.909..., about 10.91 km/h.

Check against the pace: 60 / 5.5 = 10.909... kilometres in one hour, the same value.

Python
distance = float(input('Distance (km): '))
minutes = int(input('Minutes: '))
seconds = int(input('Seconds: '))
total_min = minutes + seconds / 60
pace = total_min / distance
speed = distance / total_min * 60
print('Pace:', pace, 'min/km')
print('Speed:', round(speed, 2), 'km/h')

Exercise 8: Five statements to correct

10 answers to check

Each statement below was written on a unit test. Say whether it is true or false; if it is false, correct it. In every case, give the value asked, which supports your answer.

  • a) « After x = 7, the line x = x + 1 is an error, since no number is equal to itself plus one. » Give the value of x after the two lines.
  • b) « In Python, 15 / 5 gives the integer 3. » Give the type of 15 / 5.
  • c) « The expression -2 ** 4 is equal to 16. » Give its value.
  • d) « For a = 6 and b = 4, the expressions (a + b) / 2 and a + b / 2 do not give the same value. » Give the value of a + b / 2.
  • e) « A name written in capital letters, such as MAX_SEATS = 30, makes a constant that Python refuses to change. » Give what print(MAX_SEATS) displays after the lines MAX_SEATS = 30 and MAX_SEATS = 35.

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) False: x = x + 1 is an assignment, x becomes 8
  • b) False: 15 / 5 is the float 3.0
  • c) False: -2 ** 4 = -16
  • d) True: 5.0 and 8.0
  • e) False: Python displays 35; the capitals are a convention
a)

False. x = x + 1 is an assignment, not an equation: Python computes 7 + 1 = 8 and stores 8 in x.

Correct statement: « After x = 7 and x = x + 1, x holds 8. »

b)

False. / always gives a float in Python: 15 / 5 = 3.0, of type float.

The integer 3 is the value of 15 // 5. In Java, 15 / 5 between two int does give the int 3.

Correct statement: « In Python, 15 / 5 gives the float 3.0. »

c)

False. ** runs before the minus sign written in front: -2 ** 4 = -(2 ** 4) = -16.

Correct statement: « -2 ** 4 is equal to -16; (-2) ** 4 is equal to 16. »

d)

True. (a + b) / 2 = 10 / 2 = 5.0, while a + b / 2 = 6 + 2.0 = 8.0: the division runs first.

An average of two values needs the brackets; without them, only b is halved.

e)

False. In Python, the capitals are a naming convention: they tell the reader « do not change this value », and Python accepts MAX_SEATS = 35 without any message. print displays 35.

Correct statement: « Capital letters mark a constant for the reader; the program itself must never reassign it. » In Java, the word final makes the compiler refuse a second assignment.

Exercise 9: Problem: scaling a recipe, / against //

11 answers to check

A recipe for 4 servings uses 250 g of flour and 300 mL of milk. A program reads the number of servings wanted and displays the quantities.

Python
BASE_SERVINGS = 4                      # line 1
FLOUR_G = 250                          # line 2
MILK_ML = 300                          # line 3
servings = int(input('Servings: '))    # line 4
factor = servings // BASE_SERVINGS     # line 5
flour = FLOUR_G * factor               # line 6
milk = MILK_ML * factor                # line 7
print('Flour:', flour, 'g')            # line 8
print('Milk:', milk, 'mL')             # line 9
  • a) The user types 6. Give the values of factor and of flour. Does Python report an error?
  • b) The user types 3. How many grams of flour are displayed?
  • c) Correct line 5. For 6 servings, give factor, then the flour and the milk displayed.
  • d) After the correction, how many grams of flour are displayed for 10 servings, and why does the number end in .0?
  • e) A classmate writes line 5 as factor = BASE_SERVINGS / servings. Give the flour displayed for 6 servings, to the hundredth, and say what this result shows.

Type your answers, the page tells you right or wrong 0/11

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) factor = 1, flour = 250; no error
  • b) 0 g
  • c) factor = 1.5; Flour: 375.0 g, Milk: 450.0 mL
  • d) 625.0: factor = 10 / 4 = 2.5 is a float
  • e) About 166.67 g: less flour for more servings, so the ratio is upside down

A recipe is scaled by a ratio, the servings wanted divided by the servings of the recipe; that ratio needs true division, /.

a)

factor = 6 // 4 = 1: // keeps the whole number of times 4 goes into 6 and drops the rest.

flour = 250 × 1 = 250, the quantity for 4 servings.

No error: the program runs to the end and displays Flour: 250 g. This is a logic error: Python gives no warning, and a comparison with the expected result reveals it.

b)

factor = 3 // 4 = 0, so flour = 250 × 0 = 0: the program displays Flour: 0 g.

Pitfall: testing only with 4 or 8 servings, where // and / agree. A test with a number that is not a multiple of 4 exposes the bug.

c)

Line 5 becomes factor = servings / BASE_SERVINGS.

factor = 6 / 4 = 1.5, flour = 250 × 1.5 = 375.0 and milk = 300 × 1.5 = 450.0.

The program displays Flour: 375.0 g and Milk: 450.0 mL.

d)

factor = 10 / 4 = 2.5, so flour = 250 × 2.5 = 625.0.

The number ends in .0 because factor is a float, and a product with a float is a float, even when its value is whole.

e)

factor = 4 / 6 = 0.666..., so flour = 250 × 0.666... = 166.67 g to the hundredth.

Check the direction: more servings must mean more flour, and 166.67 g is less than the 250 g of 4 servings. The ratio is upside down; dividing the servings wanted by the base gives 375.0 g.

Python
BASE_SERVINGS = 4
FLOUR_G = 250
MILK_ML = 300
servings = int(input('Servings: '))
factor = servings / BASE_SERVINGS
flour = FLOUR_G * factor
milk = MILK_ML * factor
print('Flour:', flour, 'g')
print('Milk:', milk, 'mL')

Exercise 10: Problem: a time-lapse camera, from the statement to the program

6 answers to check

A time-lapse camera takes one photo at the end of each interval of a fixed number of seconds, from the start of the shoot to its end: no photo at 0 s, and one photo at the end of the last interval. The video then shows the photos at 30 frames per second, one frame being one photo.

Write a program that reads the length of the shoot in hours (a decimal number is allowed) and the interval in whole seconds, then displays the number of photos and the length of the video in seconds. The 30 frames per second is a constant of the program.

...0 s6 s12 s18 s8994 s9000 sstartphoto 1photo 2photo 3last photo2.5 h = 9000 s, one photo at the end of every 6 s
  • a) Write the program. How many photos does it display for a shoot of 2.5 h with one photo every 6 s?
  • b) How long is the video, in seconds?
  • c) A first version computes photos = hours * 3600 // interval. What does it display for the number of photos, with the same inputs?
  • d) A shoot of 45 minutes is typed as 0.75, with one photo every 4 s. Give the number of photos and the length of the video.
  • e) The video must last at least 60 s, with one photo every 6 s. Working backwards from the video, what is the shortest shoot, in hours?

Type your answers, the page tells you right or wrong 0/6

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 1500 photos
  • b) 50.0 s
  • c) 1500.0: hours * 3600 is a float, and // between floats gives a float
  • d) 675 photos, 22.5 s of video
  • e) 3 h

The IPO chart first. Input: the hours, a float, and the interval, an int. Processing: convert the hours into seconds, count the intervals, divide by the frame rate. Output: the photos, a whole number, and the video length. The program is below.

a)

2.5 h = 2.5 × 3600 = 9000 s. One photo at the end of each 6-second interval: 9000 // 6 = 1500 photos.

total_s = int(hours * 3600) makes the number of seconds an int, so photos is an int and the program displays Photos: 1500.

With a photo also at 0 s, there would be 1501: the statement settles this by saying no photo at 0 s.

b)

video_s = 1500 / 30 = 50.0, and the program displays Video: 50.0 s. The value is a float because / always gives one.

c)

hours * 3600 = 9000.0 is a float, since hours is a float; * and // have the same rank, so 9000.0 // 6 is computed next and gives 1500.0, a float.

The program displays Photos: 1500.0, a number of photos with a decimal point. The value is right, the type is not: int() around the seconds fixes it.

d)

0.75 × 3600 = 2700 s, and 2700 // 4 = 675 photos.

The video lasts 675 / 30 = 22.5 s.

e)

Work from the result to the data. 60 s of video at 30 frames per second needs 60 × 30 = 1800 photos.

1800 photos at one every 6 s take 1800 × 6 = 10800 s, and 10800 / 3600 = 3 h.

Check with the program: 3 h gives 10800 // 6 = 1800 photos and 1800 / 30 = 60.0 s.

Python
FPS = 30   # frames (photos) per second of video
hours = float(input('Length of the shoot (h): '))
interval = int(input('Seconds between photos: '))
total_s = int(hours * 3600)
photos = total_s // interval
video_s = photos / FPS
print('Photos:', photos)
print('Video:', video_s, 's')
Something missing from this set? A type of exercise your teacher gives, a problem you are stuck on, a mistake you spotted: tell me, I read every request.

Sending goes through your free space: that is how I can answer you and tell you when the exercise is added. An email is enough, no password. Create your space. Rather not create an account? Write to me directly.

What is it about?
I read every request myself, nobody else sees it. No need to write your name or your school.
When your request is dealt with, you hear about it by email and in your space.

By sending, you agree that I read your request to answer it. It is kept with your account, erased with it, and never published: privacy policy.

© Ahmed Squalli Houssaini. Exercise set published at www.letuteurscientifique.ca/en/exercices/ics3u-variables-data-types-expressions. Free for personal and classroom use; republishing it elsewhere requires written permission (legal notice).

Preparing for an ICS3U unit test?

I tutor Grade 11 computer science in English or in French, online. Get in touch for a first session: tracing by hand and choosing types come back in every later unit of the course.

Site by Studio Squalli