KS41CP2 6.2 32 min read 10 question quiz 13 exam marks
Programming Fundamentals in Python
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 = 10print("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.
Swipe sideways to see the whole picture.
= stores a value in a variable: the name on the left, the value on the right.
A variable is a labelled box with a name, a value and a data type.
The value can change. age = age + 1 takes the 15 out and puts 16 in.
A constant holds a value that must never change. By convention it is written in capitals.
Names use letters, digits and underscores. No spaces, and no digit first.
The name stays. The value is what you can swap.
Swipe sideways to see the whole picture.
Five data types: integer, real, Boolean, character and string.
A phone number is a string: you never add them, and a number would lose the leading 0.
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.
Swipe sideways to see the whole picture.
int() turns text into a whole number.
int() on a float cuts off the decimals. It does not round.
str() turns a number into text.
float() turns text into a decimal number.
input() always returns text, so convert it before doing sums.
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
Operator
Meaning
Example
Result
+
Add
7 + 2
9
-
Subtract
7 - 2
5
*
Multiply
7 * 2
14
/
Divide, always giving a float
7 / 2
3.5
//
Integer division
7 // 2
3
%
Modulus, the remainder
7 % 2
1
**
To the power of
2 ** 3
8
// 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 >= 13and 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":.
Swipe sideways to see the whole picture.
Arithmetic: + - * / then DIV, MOD and power.
DIV is how many whole times it goes in. MOD is what is left over.
Comparisons ask a question, and the answer is always True or False.
= 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 inrange(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.
Swipe sideways to see the whole picture.
Sequence: instructions run in order, each one once, from the top down.
Selection: a condition is tested and only one branch of the program runs.
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=652ifscore>=70:3print("A")4elifscore>=60:5print("B")6else:7print("C")Where does 65 go?65score >= 70Falseskip "A"score >= 60Trueprints "B"elsenever reachedfirst True branch winsOrder mattersTest the strictest condition first.ifscore>=50:# catches 90 too!print("C")a 90 would get the C: the first test is True1234
Swipe sideways to see the whole picture.
The code: if, elif and else test one condition after another.
Follow the value 65 down: each test is True or False, in order.
The first True test runs its block, and the rest are skipped.
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.py1forlapinrange(5):2print("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=32whilebattery>0:3battery=battery-1battery = 33 > 0 Truebattery = 22 > 0 Truebattery = 11 > 0 Truebattery = 00 > 0 Falsestopsif battery never changed, the loop would never stop12
Swipe sideways to see the whole picture.
for repeats a set number of times. range(5) gives 0, 1, 2, 3, 4: five laps.
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
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
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.