ICS3U Computer Science • Ontario Grade 11

Revision sheet: variables, data types and expressions (ICS3U)

This sheet is not a summary of the first chapter of ICS3U, Introduction to Computer Science, Grade 11: you already have your notes.

What the sheet covers

It answers one question only, what makes students lose marks on variables, data types and expressions, and which precise gesture avoids each loss.

The chapter looks easy, and its mistakes are silent: a program that joins two numbers instead of adding them, or divides with // instead of /, runs to the end and displays a wrong result without any error message. The code is in Python 3, and every value on this sheet comes from a program that was run.

  • 8 mistakes that cost marks
  • 4 figures
  • 15 min reading
Do the chapter's exercises

The thread of the chapter

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 its left; the type of each value decides what an operator does.

Topics covered

  • Variable
  • Constant
  • Assignment statement
  • Data type
  • Integer and floating point number
  • String concatenation
  • Boolean value
  • Arithmetic operators
  • Order of operations
  • User input and screen output
  • Input-process-output model
  • Trace table

The essentials

A variable is a box, and = fills it

  • • A variable is a name attached to one value. It holds one value at a time: a new assignment replaces the old value, which is lost.
  • • = is the assignment operator. Python first computes the expression on the right, with the values the variables hold at that moment, then stores the result in the variable on the left.
  • • So count = count + 1 is a normal line: it adds 1 to count. The left side names the variable that receives the value; an expression such as count * 2 cannot be there.
  • • A variable holds a value, not a formula: if total = price * 2 ran before price changed, total keeps its old value.
  • • A program runs from top to bottom. A variable used before the line that assigns it stops the program with a NameError.
Before line 2count5After line 2count6right side first:count + 1 = 5 + 1 = 6then store 6 in count
Line 2 is count = count + 1: Python reads count (5), computes 5 + 1 = 6, then stores 6 in the same box. The old value 5 is gone.

In a trace table, write a value only on the line that changes it, and compute each right side with the values in the rows above.

The type decides what the operator does

  • • int: a whole number, 42. float: a number with a decimal point, 42.0. str: text between quotes, '42'. bool: True or False, without quotes.
  • • One float in an operation makes the result a float: 5 * 2.0 is 10.0.
  • • On int and float values, / always gives a float, even when the division is exact: 12 / 4 is 3.0. // gives the whole quotient and % the remainder: 23 // 5 is 4 and 23 % 5 is 3.
  • • + adds two numbers but joins two str: '12' + '30' is '1230', which is called concatenation.
  • • input() always returns a str. int(input()) for a count, float(input()) for a measure or an amount.
  • • Data made of digits that you never compute with, and whose leading zeros matter (a card number, a phone number), belongs in a str.

The rules in table form

Each row reads from left to right: the assumptions, then the result. A red cell is not an answer, it is the finding that the form settles nothing and the instruction to rewrite it. Every case is followed by a worked example.

Python's order of operations, from first to last

Each line is one rank; within a rank, the grouping column decides. Every example was run in Python 3.

RankOperatorsGrouping
1 brackets ( ) innermost first

Example: (6 + 4) * 3 is 30, while 6 + 4 * 3 is 18.

2 ** right to left

Example: 2 ** 3 ** 2 is 2 ** 9 = 512, not 8 ** 2 = 64.

3 minus sign in front after **

Example: -6 ** 2 is -(6 ** 2) = -36; (-6) ** 2 is 36.

4 * / // % left to right

Example: 18 / 3 * 2 is 6.0 * 2 = 12.0, not 18 / 6 = 3.0.

5 + - left to right

Example: 10 - 4 - 3 is 3, not 10 - 1 = 9.

When a line is hard to read, add brackets: they cost nothing and they show the reader which operation runs first.

The mistakes that cost marks

These are the errors I correct most often in session. Each one costs marks on a paper, even when the reasoning behind it is right.

1. Reading = as an equation in a trace

every row of the trace from that line on

What not to write

“Line 3, score = score + bonus, is only true if bonus is 0, so score stays 4.”

What to write

“Line 3: score + bonus = 4 + 12 = 16, then score holds 16.”

Why: = is an instruction: compute the right side, then store. The test of equality is ==, which belongs to the chapter on selection.

2. Adding two values read by input()

every test case of the program, with no error message to warn you

What not to write

“laps = input('Laps: '), more = input('More: '), then total = laps + more: for 8 and 5, total is 13.”

What to write

“input() returns '8' and '5', so laps + more is '85'. Write laps = int(input('Laps: ')) and more = int(input('More: ')): total is 13.”

input() alone: strlaps'8'more'5'total'85'int(input()): intlaps8more5total13
On the left, input() alone fills the boxes with the str '8' and '5', and + joins them into '85'. On the right, int() turns them into numbers, and + adds them: 13.

Why: The value typed is right, only its type is wrong: + between two str joins them. The program runs to the end and displays 85.

3. Expecting an int from /

1 mark per printed line in a predicted output

What not to write

“print(20 / 4) displays 5.”

What to write

“20 / 4 is 5.0, a float, so print displays 5.0. 20 // 4 is the int 5.”

Why: In Python, / is true division and gives a float on int and float values. In Java, two int divided with / give an int: 20 / 4 is 5 and 21 / 4 is 5 too.

4. A minus sign in front of a power

1 mark, and every value computed from it

What not to write

“-6 ** 2 is 36, since a negative number squared is positive.”

What to write

“** runs before the minus sign: -6 ** 2 is -(6 ** 2) = -36. To square -6, write (-6) ** 2, which is 36.”

Why: The minus sign in front is an operation of lower rank than **. A negative number squared is positive, but -6 ** 2 squares 6, not -6.

5. A formula typed without its brackets

1 to 2 marks, and a program that is wrong for every input except start = 0

What not to write

“midpoint = start + end / 2 gives 20.0 for start = 10 and end = 30.”

What to write

“start + end / 2 is 10 + 15.0 = 25.0. The midpoint is (start + end) / 2 = 20.0.”

Why: / runs before +, so only end is halved. On paper the fraction bar groups the numerator; in a line of code, the brackets must do it.

6. Exchanging two variables in two lines

the value lost, and every line that uses it

What not to write

“gold = silver, then silver = gold: the two names are exchanged.”

What to write

“temp = gold, then gold = silver, then silver = temp. In Python, gold, silver = silver, gold also works.”

Linegoldsilver1'Leo'2'Mia'3'Mia'4'Mia'gold = silver, silver = goldLinegoldsilvertemp1'Leo'2'Mia'3'Leo'4'Mia'5'Leo'With a temporary variable
On the left, line 3 overwrites 'Leo' and line 4 copies 'Mia' back: both hold 'Mia'. On the right, temp keeps 'Leo' until line 5 puts it in silver.

Why: The first line overwrites gold before its value is saved; the second line copies the value that is already in both. The single Python line evaluates its whole right side first.

7. Using // where the statement needs a ratio

1 to 2 marks, and the bug hides when the test data divides exactly

What not to write

“average = total // count gives the average: for a total of 17 and a count of 4, it is 4.”

What to write

“total / count = 17 / 4 = 4.25. // drops the 0.25 without any message.”

Why: // gives the whole number of times count goes into total: it is the right operator for full boxes or full minutes, not for a ratio or an average.

8. Storing an identification number as an int

1 mark on a type question, and a wrong record in the program

What not to write

“student = int(input('Student number: ')), then print(student) shows 0072315.”

What to write

“int('0072315') is 72315: the zeros are lost. A number you never compute with stays a str: student = input('Student number: ').”

Why: An int has no leading zeros. The type follows what the program does with the data, not the characters it is made of.

Which method to choose

Which type for this piece of data?

Ask what the program will do with the data, not what it looks like.

  • If a count of whole things: books, laps, photos, servings → int, read with int(input())

    Example: servings = int(input('Servings: '))

  • If a measure or an amount that can have decimals: a mass, a time in hours, a price → float, read with float(input())

    Example: mass = float(input('Mass (g): ')) accepts 84 and 84.5

  • If text, or digits you never compute with: a name, a card number, a postal code → str, read with input() alone

    Example: card = input('Card: ') keeps '0045812'

  • If an answer that is yes or no: valid, paid, finished → bool, True or False without quotes

    Example: card_valid = True

A fixed value used by the formulas, such as a price per gram, is a constant: capital letters, defined once at the top.

/, // or %?

Read what the statement asks for.

  • If a ratio, an average, a rate, a scale factor → /, which keeps the decimals and gives a float

    Example: factor = 6 / 4 = 1.5

  • If how many full groups: full boxes, full minutes, photos taken → //, on positive whole numbers

    Example: 9000 // 6 = 1500 photos

  • If what is left after the full groups → %, on positive whole numbers

    Example: 23 % 5 = 3

How the answer is expected to be written

A marker ticks steps. Here they are in order, with the concluding sentence expected word for word.

Tracing a program by hand on a unit test

When to use it: « What does this program display? » or « Give the value of x after line 5 », on six to fifteen lines

  1. 1 Draw a table: one column per variable, one column for the output, one row per line executed.
  2. 2 On each 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 only.
  3. 3 Write each value with its type: '12' with quotes for a str, 3.0 for a float, 3 for an int.
  4. 4 At each print, copy the exact characters displayed, one space between two values separated by a comma.
  5. 5 Answer with the last value of the column, not the value you expected the program to give.

Concluding sentence

“Line 4: bonus = bonus - score = 12 - 16 = -4, since line 3 has already stored 16 in score.”

The trap: Computing a row with the value a variable had at the start instead of its value in the row above.

Marking: A common split: 1 mark per printed line, and the rest of the trace lost from the first wrong row.

Writing a short input-process-output program

When to use it: « Write a program that reads ... and displays ... », then « give its output for ... »

  1. 1 Fill the IPO chart first: the inputs with their types, the formulas, the outputs.
  2. 2 Write the fixed values as constants in capital letters at the top, with a comment that gives their unit.
  3. 3 Read each input with a prompt and the right conversion: int(input()) or float(input()).
  4. 4 Write each formula with its brackets, in the order the values are needed.
  5. 5 Display the result with a label and a unit, then trace the program on the input of the statement.

Concluding sentence

“For 2.5 h and one photo every 6 s, total_s = 9000, photos = 9000 // 6 = 1500 and the video lasts 1500 / 30 = 50.0 s.”

The trap: Giving the output without tracing the program you wrote: the marker checks that the number comes from your code.

Marking: A common split: 1 mark for the inputs and their conversion, 1 for the formulas, 1 for the output with its unit.

Check before you hand in

Five minutes of checking recover more marks than one more problem started in a hurry.

  • The decimal point of a division

    Every value that comes from / is a float: in a predicted output, it is written with a decimal point.

    18 / 6 displays 3.0, not 3; 2.5 * 3600 // 6 displays 1500.0, because one of its values is a float.

  • The size of the answer

    Before writing a result, ask whether it is possible in the situation of the statement.

    A runner's pace of 0.19 minute per kilometre is about 11 seconds per kilometre: impossible, so a unit or a bracket is wrong.

  • Two values after an exchange

    After an exchange of two variables, both original values must still appear in the trace.

    If indoor and outdoor both end at 21.0, the reading -6.5 was overwritten: a temporary variable is missing.

  • A second set of test data

    Run the trace again on data that does not divide exactly and that is not symmetric.

    A recipe scaled with // gives the right answer for 8 servings and 0 g of flour for 3 servings.

The typical problem, taken apart

Splitting the fuel cost of a road trip

Write a program that splits the fuel cost of a road trip between friends: it reads the distance in kilometres, the fuel use of the car in litres per 100 km, the price of a litre in dollars and the number of friends, then displays what each one pays.

Trace it on a trip of 420 km, a fuel use of 7.5 L/100 km, a price of 1.60 dollars per litre and 3 friends.

Python
distance = float(input('Distance (km): '))
per_100 = float(input('Fuel use (L/100 km): '))
price = float(input('Price (dollars/L): '))
friends = int(input('Friends: '))
litres = distance * per_100 / 100
cost = litres * price
share = cost / friends
print('Each pays', round(share, 2), 'dollars')

Step 1

IPO chart. Input: the distance, the fuel use and the price, three float, and the number of friends, an int. Processing: the litres, the cost, the share. Output: the share, with its unit.

Why

Choosing the types before writing tells you which conversion each input line needs: a number of friends is a count, a price has decimals.

Step 2

litres = 420.0 × 7.5 / 100 = 3150.0 / 100 = 31.5

Why

* and / have the same rank and run from left to right; the division by 100 comes from the unit, litres per 100 km.

Step 3

cost = 31.5 × 1.6 = 50.4, which Python stores as 50.400000000000006

Why

A float can carry a tiny rounding error in its last digit; the reason lies in how floats are stored, studied in ICS4U. The display, not the value, is rounded.

Step 4

share = cost / 3 = 16.8, and the last line displays Each pays 16.8 dollars

LineVariableValueType1distance420.0float2per_1007.5float3price1.6float4friends3int5litres31.5float6cost50.4float7share16.8float8outputEach pays 16.8 dollarstextTrace with types, inputs 420, 7.5, 1.60 and 3

Why

round(share, 2) keeps at most two decimals for the screen; the trace table records each value and its type.

The conclusion, written out

“For 420 km at 7.5 L/100 km and 1.60 dollars per litre, the fuel costs 50.40 dollars and each of the 3 friends pays 16.8 dollars.”

The classic mistake on this problem: Reading the number of friends with input() alone: cost / friends then divides a float by a str, and the program stops with a TypeError on that line.

Learn by heart

  • • = computes the right side first, then stores it on the left: x = x + 1 adds 1 to x.
  • • A variable holds a value, not a formula; a line that has run does not run again.
  • • int 42, float 42.0, str '42', bool True. Quotes make a str.
  • • / gives a float on int and float values; // and % give the quotient and the remainder of whole numbers.
  • • Rank: brackets, **, minus sign in front, * / // %, + -. ** from right to left, the others from left to right.
  • • input() returns a str: int(input()) or float(input()) before any arithmetic.
  • • Constants in capital letters, defined once at the top.
  • • Exchange: temp = a, a = b, b = temp.

Frequently asked questions

Why does x = x + 1 work in a program when it is impossible in algebra?

Because the equal sign of a program is an assignment, not an equation. Python first computes the right side with the value x holds now, then stores the result back in x. If x held 7, the line computes 8 and x now holds 8. The test of equality is written with two equal signs and only compares, it never changes a variable.

Why does my Python program join two numbers instead of adding them?

Because input always returns a string, even when the user types digits. Two strings joined by the plus sign are put end to end, so 12 and 30 give 1230. Convert each input before computing: int of input for a whole number, float of input for a number that may have decimals. The sum of 12 and 30 is then 42.

What is the difference between / and // in Python?

A single slash is true division and always gives a float, even when the division is exact: 12 divided by 4 gives 3.0. A double slash gives the whole number of times the divisor goes in and drops the rest: 23 double slash 5 gives 4. Use the single slash for a ratio, an average or a scale factor, and the double slash for full groups.

Why is -6 ** 2 equal to -36 in Python?

Because the power operator has a higher rank than the minus sign written in front of a number. Python squares 6 first, which gives 36, then applies the minus sign. To square negative 6, put it in brackets: the bracketed version gives 36. The double star is also grouped from right to left, so 2 ** 3 ** 2 is 2 to the power 9.

How do you choose between int, float, str and bool for a variable?

Ask what the program will do with the data. A count of whole things is an int, a measure or an amount with decimals is a float, text is a str, and a yes or no answer is a bool. Digits you never compute with, such as a card number or a phone number, stay a str, because an int would drop their leading zeros.

Mark this sheet as read or add it to your favourites: a free account, no password, keeps your read sheets and favourites from one visit to the next, tells you which chapter to tackle next and lets you ask for the method or exercise you are missing. Create your space, an email is enough.

Practise it

Corrected exercises: Variables, data types and expressions, ICS3U

A method is proved on a paper, not on a sheet. The set for the same chapter takes each of these traps into a problem, with the solution written out step by step.

  • 12 corrected exercises
  • 120 points
  • 150 minutes
Do the exercises
Something missing from this sheet? A method, a trap, an exercise to practise it, 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. Revision sheet published at www.letuteurscientifique.ca/en/fiches/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.

Site by Studio Squalli