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.
name = "Amira"
age = 15
average = 68.4
member = TruePython 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.
VAT_RATE = 0.2
MAX_ATTEMPTS = 3Reading input
name = input("What is your name? ")
age = int(input("How old are you? "))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
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.
- = 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.
- 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().
- 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.
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.
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.
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: + - * / 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.
Sequence, selection and iteration
Sequence
Statements run in the order written. A variable must be given a value before it is used.
Selection
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.
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:
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:
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.
- 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.
- 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.
- 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.
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.
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
- 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.
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
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.
- LA variable's value can change while the program is running
- LA constant holds a value that should not change while the program runs
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.
- 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
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.
- 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
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.
- 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(...))
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.