KS41CP2 6.2 32 min read 10 question quiz 13 exam marks

Programming Fundamentals in Python

Everything Paper 2 assumes you can do without thinking: variables and types, every operator, the three constructs, and reading input safely. Every example here runs in the browser.

Variables, constants and data types

A variable is a named location whose value can change. Python creates one the moment you assign to it.

Python
name = "Amira"
age = 15
average = 68.4
member = True

Python decides the type from the value: str, int, float and bool respectively. Check one with type().

A constant is a value that should not change. Python has no separate keyword for one, so the convention is a name in capitals, and the convention is what the exam expects to see.

Python
VAT_RATE = 0.2
MAX_ATTEMPTS = 3

Reading input

Python
name = input("What is your name? ")
age = int(input("How old are you? "))
input() always returns a string

Even when the user types 15, what comes back is the two characters "1" and "5". Comparing that with a number or doing arithmetic on it will not behave as you expect, which is why int() or float() wraps it. This is the single most common cause of a Paper 2 program not working.

Output

Python
score = 7
total = 10
print("You scored", score, "out of", total)
print(f"You scored {score} out of {total}")

The second form is an f-string, and it is the clearer one once a message contains more than a couple of values.

Variables as labelled boxes, with the code that makes themSix lines of code on the left and the boxes they create on the right. The equals sign is assignment: it stores the value on its right in the variable named on its left. Every variable is like a labelled box with a name, a value and a data type. name holds the string Asha, age holds the whole number 15, price holds the decimal 2.5 and passed holds True. The fifth line, age equals age plus one, takes the 15 out and puts 16 in, which shows that the value of a variable can change while its name stays the same. PI is a constant: a value that must never change, written in capitals by convention and shown with a padlock. A card at the bottom left gives the naming rules: use letters, digits and underscores, do not start with a digit and never use a space.variables.py1name = "Asha"2age = 153price = 2.504passed = True5age = age + 16PI = 3.14159Naming a variabletotal_scorewords joined by _age2digits are fine inside2nd_placecannot start with a digitmy scoreno spacesWhat the computer keepsname"Asha"strage16intreplaces 15price2.5floatpassedTrueboolPI3.14159a constant: never changes12345
  1. = stores a value in a variable: the name on the left, the value on the right.
  2. A variable is a labelled box with a name, a value and a data type.
  3. The value can change. age = age + 1 takes the 15 out and puts 16 in.
  4. A constant holds a value that must never change. By convention it is written in capitals.
  5. Names use letters, digits and underscores. No spaces, and no digit first.
The name stays. The value is what you can swap.
The data types, and changing one into anotherThe five basic data types, one card each. An integer is a whole number such as 42, written int in Python. A real number has a decimal point such as 3.14, written float. A Boolean has only two values, True and False, shown as a switch that is on and a switch that is off. A character is a single symbol such as the letter A, and a string is text inside quote marks. A phone number is stored as a string, because you never do arithmetic on it and because storing it as a number would drop the leading zero, turning 07700 into 7700. Casting changes a value from one type to another: int of the text 42 gives the number 42, str of the number 42 gives the text 42, and int of 3.9 gives 3 because the decimal part is cut off rather than rounded.Integer42-7 0 2025whole numbersintReal3.140.5 -2.75with a decimal pointfloatBooleanTrue Falseonly two valuesboolCharacterAz 7 ?one single symbolstrString"Hi""07700 900123"text in quotesstr1A phone number is a string07700900123you never add phone numbersa number would lose the 007700 as a number = 7700so it is stored as text2Casting: changing type"42"int()42to a whole number42str()"42"to text3.9int()3cuts off the .93
  1. Five data types: integer, real, Boolean, character and string.
  2. A phone number is a string: you never add them, and a number would lose the leading 0.
  3. Casting changes a value from one type to another: int(), str(), float().
Choose the type from what you will do with the value, not from how it looks.
Casting between types: int, float and str, and when it failsCasting converts a value from one data type to another. int of the text 42 gives the whole number 42. int of 3.7 gives 3, because it cuts off the decimal part and does not round. str of the number 5 gives the text 5, so it can be joined to words. float of the text 3.14 gives the decimal number 3.14. The input function always gives back text, so a number typed by a user must be converted, as in age equals int of input. Some conversions fail: int of the text hello raises a ValueError, so input should be checked before it is converted.int("42")42stringint()42integertext to a whole numberint(3.7)3.7floatint()3integercuts off the decimal part: it does not roundstr(5)5integerstr()"5"stringa number to text, so it can be joined to wordsfloat("3.14")"3.14"stringfloat()3.14floattext to a decimal number1234input() always gives text5age = int(input("Age? "))print(age + 1)convert it before doing sums with itSome conversions fail6Output>>> int("hello")ValueError: invalid literalso check the input before converting it
  1. int() turns text into a whole number.
  2. int() on a float cuts off the decimals. It does not round.
  3. str() turns a number into text.
  4. float() turns text into a decimal number.
  5. input() always returns text, so convert it before doing sums.
  6. A conversion that does not make sense raises an error, so validate first.
Casting does not change the original. It makes a new value of the type you asked for.

Operators

Arithmetic

OperatorMeaningExampleResult
+Add7 + 29
-Subtract7 - 25
*Multiply7 * 214
/Divide, always giving a float7 / 23.5
//Integer division7 // 23
%Modulus, the remainder7 % 21
**To the power of2 ** 38

// and % are worth real marks. seconds // 60 gives whole minutes, seconds % 60 gives the seconds left over, n % 2 == 0 tests for even, and n % 10 gives the last digit.

Comparison

== equal to, != not equal to, <, >, <=, >=. Each of these produces a Boolean.

One equals sign assigns, two compare

x = 5 puts 5 into x. x == 5 asks whether x holds 5. Writing one where you meant the other is the most common single error in Python.

Logical

and is True only if both sides are True. or is True if at least one is. not reverses.

Python
if age >= 13 and age <= 19:
    print("teenager")

if grade == "A" or "B": does not work. Each side of or must be a complete comparison, so it has to be if grade == "A" or grade == "B":.

Arithmetic and comparison operatorsThe arithmetic operators as seven cards: plus, minus, multiply, divide, DIV, MOD and power, each with a worked example. Seven divided by two is 3.5. DIV gives the whole number of times it goes in, so 7 DIV 2 is 3, written with a double slash in Python, and MOD gives what is left over, so 7 MOD 2 is 1, written with a percent sign. A picture shows it as seven cookies shared between two people: three each, and one left over. Below, the comparison operators give True or False: 5 equals 5 is True, 5 is not equal to 5 is False, 5 greater than or equal to 6 is False and 5 less than 6 is True. A warning shows the commonest slip: a single equals sign stores a value, while a double equals sign asks whether two values are equal.+add7 + 2= 9-subtract7 - 2= 5*multiply7 * 2= 14/divide7 / 2= 3.5//DIV7 // 2= 3%MOD7 % 2= 1**power2 ** 3= 81DIV and MOD: 7 cookies, 2 people3 each3 each1 left over7 // 2 = 3 (DIV)7 % 2 = 1 (MOD)2Comparing: True or False5 == 5True5 != 5False5 >= 6False5 < 6True= stores a value== asks "are they equal?"34
  1. Arithmetic: + - * / then DIV, MOD and power.
  2. DIV is how many whole times it goes in. MOD is what is left over.
  3. Comparisons ask a question, and the answer is always True or False.
  4. = stores a value. == asks whether two values are equal.
MOD is the clock operator: it is what is left when you have gone round as many times as you can.

Sequence, selection and iteration

Sequence

Statements run in the order written. A variable must be given a value before it is used.

Selection

Python
mark = int(input("Enter the mark: "))

if mark >= 70:
    grade = "Distinction"
elif mark >= 50:
    grade = "Merit"
elif mark >= 40:
    grade = "Pass"
else:
    grade = "Fail"

print(f"Grade: {grade}")

The order of the conditions is doing real work. A mark of 80 satisfies all three tests and gets Distinction only because that test is first. Reverse them and every passing student gets a Pass.

Indentation is the syntax

Python uses indentation to decide what is inside an if or a loop. A line indented by the wrong amount is a different program, not an untidy one.

Iteration

Count controlled, when the number of repeats is known:

Python
for i in range(1, 6):
    print(i, i * i)

for letter in "PYTHON":
    print(letter)

range(1, 6) gives 1, 2, 3, 4, 5. It stops before the second number, which is the detail that causes most off by one errors.

Condition controlled, when it is not:

Python
total = 0
number = int(input("Enter a number, or 0 to stop: "))
while number != 0:
    total = total + number
    number = int(input("Enter a number, or 0 to stop: "))
print("Total:", total)

Two things make a while loop work: the variable in the condition must have a value before the loop starts, and something inside the loop must be able to change it. Miss either and you have an infinite loop.

The three constructs: sequence, selection and iterationEvery program is built from three constructs, one card each. Sequence is steps taken one after another in order: wake up, brush teeth, have breakfast, and in code the lines run once each from the top down. Selection is a choice: a decision diamond asks whether it is raining, and only one of the two branches is taken, an umbrella if yes and sunglasses if no, written in code as if and else. Iteration is repetition: a loop arrow carries Pixel round again, here five times, written as a for loop over range of five, and when the loop has finished the program carries on with the next line.SequenceSelectionIteration1wake up2brush teeth3have breakfastprint("Wake up")print("Brush teeth")print("Have breakfast")every line runs once,from the top downraining?yesnoumbrellasunglassesif raining:    print("Umbrella")else:    print("Sunglasses")only one branch runsdepending on the answer5 timesfor i in range(5):    print("Star jump")the block repeats,then the program moves on123
  1. Sequence: instructions run in order, each one once, from the top down.
  2. Selection: a condition is tested and only one branch of the program runs.
  3. Iteration: a block is repeated, a set number of times or until a condition changes.
Any algorithm, however big, is these three arranged in different ways.
if, elif and else: the first true branch winsA grading program with the score 65, and the route that 65 takes. The first test, score greater than or equal to 70, is False, so the block that prints A is skipped. The second test, score greater than or equal to 60, is True, so its block runs and prints B. Because a branch has been chosen, the else is never reached. Only one branch of an if, elif and else ever runs, and it is the first one whose condition is True. That is why the order of the tests matters: if a test for 50 or more had been written first, a score of 90 would satisfy it and receive the lowest grade, so the strictest condition must come first.grade.py1score = 652if score >= 70:3    print("A")4elif score >= 60:5    print("B")6else:7    print("C")Where does 65 go?65score >= 70Falseskip "A"score >= 60Trueprints "B"elsenever reachedfirst True branch winsOrder mattersTest the strictest condition first.if score >= 50:   # catches 90 too!    print("C")a 90 would get the C: the first test is True1234
  1. The code: if, elif and else test one condition after another.
  2. Follow the value 65 down: each test is True or False, in order.
  3. The first True test runs its block, and the rest are skipped.
  4. So test the strictest condition first, or an easy one will catch everything.
Conditions are checked in order, and checking stops at the first one that is True.
for loops count; while loops wait for a conditionTwo kinds of loop. A for loop repeats a set number of times. The code for lap in range of five prints Lap and the lap number, and the picture shows it as a running track with five flags numbered 0 to 4: range of five counts from 0 up to 4, so there are five laps and the value 5 is never reached. A while loop repeats until a condition becomes False. Starting with battery equal to 3, the loop checks battery greater than 0, which is True, so it takes one off the battery and goes round again, checking before every go. At battery 0 the condition is False and the loop stops. If nothing inside the loop ever changes the battery, the condition would stay True for ever, which is an infinite loop.for: repeat a set number of timesfor.py1for lap in range(5):2    print("Lap", lap)outputLap 0 Lap 1 Lap 2 Lap 3 Lap 401234range(5) counts 0, 1, 2, 3, 4: five laps, never 5lap starts at 0, finishes at 4while: repeat until a condition is Falsewhile.py1battery = 32while battery > 0:3    battery = battery - 1battery = 33 > 0 Truebattery = 22 > 0 Truebattery = 11 > 0 Truebattery = 00 > 0 Falsestopsif battery never changed, the loop would never stop12
  1. for repeats a set number of times. range(5) gives 0, 1, 2, 3, 4: five laps.
  2. while repeats until its condition is False, checked before every go round.
Use for when you know how many times. Use while when you only know when to stop.

Key terms you must be able to define

Variable
A named location in memory whose value can change while the program runs.
Constant
A value that should not change, written by convention in capitals in Python.
Casting
Converting a value from one data type to another, such as int() on a string.
Operator
A symbol representing an operation, such as arithmetic, comparison or logic.
Integer division
Division giving only the whole number part, written // in Python.
Modulus
The remainder after an integer division, written % in Python.
Selection
Choosing between paths through a program using if, elif and else.
Iteration
Repeating statements, using for when the count is known and while when it is not.
f-string
A Python string prefixed with f, in which values in braces are substituted.

Flashcards

Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.

DefineVariable
AnswerA named location in memory whose value can change while the program runs.
DefineConstant
AnswerA value that should not change, written by convention in capitals in Python.
DefineCasting
AnswerConverting a value from one data type to another, such as int() on a string.
DefineOperator
AnswerA symbol representing an operation, such as arithmetic, comparison or logic.
DefineInteger division
AnswerDivision giving only the whole number part, written // in Python.
DefineModulus
AnswerThe remainder after an integer division, written % in Python.
DefineSelection
AnswerChoosing between paths through a program using if, elif and else.
DefineIteration
AnswerRepeating statements, using for when the count is known and while when it is not.

Reach the top grade on this topic

Paper 2 is marked on a program that works, so the habits that matter are the ones that prevent it not working.

Cast every input immediately. Write int(input(...)) as one line rather than converting later, and the whole class of type error disappears.

Test the boundaries yourself. Run your program with the smallest and largest allowed value, and with one either side. Almost every logic error in a graded task shows up at a boundary and nowhere else.

Name variables so the code reads. total_price rather than tp. It costs three seconds and it is credited under maintainability.

Trace before you rewrite. When a program gives the wrong answer, add a print statement showing the value of the variable you suspect. Guessing at changes takes longer and usually introduces a second fault.

Mistakes that cost marks here

Avoid these
  • Using = where == was meant, or the reverse.
  • Forgetting to cast input() before doing arithmetic or a numeric comparison.
  • Writing if x == 1 or 2. Each side of or must be a complete comparison.
  • Expecting range(1, 5) to include 5. It stops before the second number.
  • Changing the indentation of a line and assuming it makes no difference. In Python it changes what the line belongs to.
Fun fact

Paper 2 is sat on a computer with Python 3 and a folder of starter files. You are not marked on remembering syntax you could look up, you are marked on producing a program that works, which is why practising by typing is the only preparation that counts.

Knowledge check

0 of 10 answered
1What is the value of 17 // 5 in Python?
2What is the value of 17 % 5?
3What does input() always return?
4Which values does range(1, 5) produce?
5What is wrong with if grade == 'A' or 'B':?
6What does n % 2 == 0 test?
7Which loop should be used when the number of repeats is not known in advance?
8Why does Python indentation matter?
9What is the result of print('5' + '3') in Python?
10Why should a while loop's condition variable be given a value before the loop?
Score 0 / 10

Exam-style questions

Five written questions in the style of the real paper. Write a full answer, then let the marker check it against the mark scheme.

13 marks
1State the difference between a variable and a constant.2 marks
State

Mark scheme0 / 2
  • LA variable's value can change while the program is running
  • LA constant holds a value that should not change while the program runs
Model answer

A variable is a named location whose value can be changed while the program is running. A constant holds a value that is fixed and should not be changed during the run, and in Python this is shown by writing the name in capitals.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2Write a Python program that asks the user for a number of seconds and prints the equivalent number of whole minutes and remaining seconds.4 marks
Write

Mark scheme0 / 4
  • LReads input and casts it to an integer
  • LUses integer division to find the minutes
  • LUses modulus to find the remaining seconds
  • LPrints both values with a clear message
Model answer

A correct program is: total = int(input("Enter the number of seconds: ")) then minutes = total // 60 then seconds = total % 60 then print(f"That is {minutes} minutes and {seconds} seconds"). The input must be cast with int() because input returns a string, integer division gives the number of complete minutes, and the modulus gives what is left over after those whole minutes have been taken out.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3Explain the difference between a for loop and a while loop, and give one situation in which each would be the better choice.4 marks
Explain

Mark scheme0 / 4
  • LA for loop repeats a known number of times
  • LA while loop repeats while a condition is True, for an unknown number of repeats
  • LGives a sensible for loop use, such as processing every item in a list
  • LGives a sensible while loop use, such as validating input until it is acceptable
Model answer

A for loop repeats a number of times that is known before the loop starts, which is why it is called count controlled. Working through every item in a list of forty names is a for loop task, because the length of the list is known. A while loop repeats for as long as its condition remains True, and the number of repeats is not known in advance, which makes it condition controlled. Repeatedly asking a user to enter a value until they enter a valid one is a while loop task, because there is no way to know how many attempts they will need.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4A student writes age = input("How old are you? ") and then if age >= 18:. The program crashes. Explain why and how to correct it.3 marks
Explain

Mark scheme0 / 3
  • Linput returns a string, so age holds text rather than a number
  • LComparing a string with an integer causes a type error in Python
  • LCast the input to an integer, for example age = int(input(...))
Model answer

The input function always returns a string, so after the first line age holds the characters the user typed rather than a number. The comparison then asks Python to decide whether a string is greater than or equal to an integer, which is not a comparison Python can make, so it raises a TypeError and the program stops. The correction is to convert the input as it is read, by writing age = int(input("How old are you? ")), after which the comparison is between two integers and works as intended.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 13