CPX17Python Basics: Data Types, Variables, Operators, Input and Output
Edexcel 1CP2 · 6.2.1
How a Paper 2 program is laid out
Paper 2 is on screen. You open Pearson’s starting files in your own IDE, change or add code, and save your work. Every file Pearson gives you uses the same layout.
Each section starts with a banner comment: # Import libraries, # Constants, # Global variables, # Subprograms, # Main program.
Lines that start # =====> are Pearson’s instructions. Put your code where they say. Don’t delete, rewrite or move the code you’re given.
Pearson’s code style: a space between a name and its brackets, as in print ("Hi") and int (input ("Age: ")), and brackets round every condition, as in if (total > 100):. Python runs fine either way. The style just makes code easier to read.
The Programming Language Subset (PLS) lists every part of Python that Pearson uses. You get it on paper and on screen in the exam, so look things up in it. Pearson never sets a task that needs more than the PLS, but valid code from outside it still earns marks.
Anything after # on a line is a comment. Comment each block of code to say what it does, not every line.
Only the sections a program needs are included, but always in this order
Worked exampleThis short program works out how much grass seed a lawn needs. Identify the parts of its layout.
# -------------------------------------------------------------------
# Constants
# -------------------------------------------------------------------
SEED_PER_M2 = 35 # Grams of seed per square metre
# -------------------------------------------------------------------
# Global variables
# -------------------------------------------------------------------
length = 0.0
width = 0.0
seedNeeded = 0.0
# -------------------------------------------------------------------
# Main program
# -------------------------------------------------------------------
length = float (input ("Length of lawn in metres: "))
width = float (input ("Width of lawn in metres: "))
seedNeeded = length * width * SEED_PER_M2
print ("You need", seedNeeded, "grams of seed")
Constants section: SEED_PER_M2 = 35a value that never changes, named in capitals
Global variables section: length, width and seedNeeded, each set to 0.0every variable is created and given a starting value before the main program
Main program: two inputs, one calculation, one outputthis is where the program actually runs
No Import libraries or Subprograms sectionsthis program doesn’t need them
For a 6 m by 4.5 m lawn the program outputs You need 945.0 grams of seed.
Exam tipExaminers take marks off for rewriting or deleting the code you were given. Add code only where the # =====> comments tell you to.
PLS
Programming Language Subset: Pearson’s list of the parts of Python 3 used in Paper 2. You have a copy in the exam.
Comment
Text after # that Python ignores. It explains the code to people reading it.
Edexcel 1CP2 · 6.3.1
Data types: integer, real, Boolean and character
Every value has a data type. Pearson names four primitive data types. The PLS gives the Python name for each.
Python has no separate character type. A character is a str holding one character. A string, such as a name, is a sequence of characters, also str.
Choose the type from the values and what the program does with them. A phone number or a code with a leading 0 is a string: it is never used in arithmetic, and an integer would lose the 0.
The first value you give a variable sets its type: total = 0.0 makes a real, total = 0 makes an integer. Keep a variable the same type for the whole program.
You can also declare a variable with its type and no value: count = int () gives 0, price = float () gives 0.0, name = str () gives an empty string.
Data type
Python
Holds
Good for
Integer
int
A whole number, negative or positive
A count of tickets, a score, an age
Real
float
A number with a fractional part
A price, a weight, a distance
Boolean
bool
One of two values: True or False
Whether a door is locked
Character
str
A single letter, digit or symbol
A grade such as "B"
Use the general name (integer, real…) or the Python name (int, float…) in comments
Worked exampleGive the data type of each value: (a) 7 / 2 (b) 7 // 2 (c) "7" (d) 7 > 2 (e) 7.0
(a) 7 / 2 is 3.5: real/ always gives a real
(b) 7 // 2 is 3: integer// is integer division
(c) "7": string (one character)the quotation marks make it text
(d) 7 > 2 is True: Booleana comparison gives True or False
(e) 7.0: realit has a decimal point, even though the fraction is 0
(a) real (b) integer (c) character/string (d) Boolean (e) real
Exam tipStart a variable that will hold a real number at 0.0, not 0. Examiners noticed students initialising reals with integers.
Integer (int)
A whole number, negative or positive.
Real (float)
A number with a fractional part (a decimal number).
Boolean (bool)
A value that can only be True or False.
Character (str)
A single letter, digit or symbol. Python stores it as a string of length 1.
Edexcel 1CP2 · 6.2.1, 6.3.2
Variables, initialisation and assignment
A variable is a named location in memory that holds a value. The value can change while the program runs.
Assignment uses =. Python works out the right-hand side first, then stores the result in the variable on the left: total = total + price.
Initialisation is giving a variable its first value. Pearson’s files initialise every global variable at the top: total = 0.0, name = "", found = False.
Assigning a new value replaces the old one, which is lost.
Identifiers (names) may use letters, digits and underscores, must start with a letter and can’t contain spaces. Upper and lower case are different: Total and total are two variables.
Pearson writes variable names in camelCase: numTickets, averageSpeed. Make names meaningful. x or a2 tell a reader nothing.
= assigns a value. == compares two values.
Worked exampleWork out the final values of apples and pears.
apples = 5
pears = apples * 2
apples = pears - 3
pears = pears + apples
apples = 5initialisation
pears = 5 × 2 = 10uses the current value of apples
apples = 10 − 3 = 7the old value, 5, is replaced
pears = 10 + 7 = 17uses the new value of apples
apples = 7, pears = 17
Exam tipIn a ‘name the part’ question, an initialisation is the first time a variable is given a value. A later line that changes it is an assignment, not an initialisation. Examiners found initialisation the hardest part to spot.
Variable
A named memory location holding a value that can change while the program runs.
Assignment
Setting or changing the value of a variable, using =.
Initialisation
Giving a variable its first (starting) value.
Identifier
The name of a variable, constant or subprogram.
camelCase
Writing a name with no spaces, each new word starting with a capital: numTickets.
Edexcel 1CP2 · 6.3.2
Constants
A constant holds a value that is set once and doesn’t change while the program runs.
Python has no true constants. By convention a name in CAPITALS (with underscores between words) is treated as a constant: MAX_SEATS = 52. Never assign it a new value later.
Put constants in the Constants section at the top of the program.
Why use a constant? If the value changes (a new price, say), you edit one line and every use updates. The name says what the number means, so the code is easier to read. And you can’t mistype the value in one of many places.
A constant can be any type: VAT_RATE = 0.2, SHOP = "Bike Hub", LF = "\n".
When a question gives you constants, use them. Typing the number itself instead (a literal) doesn’t get the mark.
Worked exampleRewrite this fragment so it uses named constants for the ticket price (£4.50) and the seat limit (52).
Exam tipExaminers keep seeing literal numbers typed in where the program already had a constant, and constants being changed as if they were variables. Both lose marks.
Constant
A named value that is set once and not changed while the program runs. Named in CAPITALS in Python.
Literal
A value typed straight into the code, such as 52 or "Yes".
Edexcel 1CP2 · 6.4.1, 6.3.1
Input and converting data types
input (prompt) shows the prompt and waits for the user to type a line. It always returns a string, even if the user types a number.
Convert straight away: age = int (input ("Enter your age: ")), height = float (input ("Height in metres: ")).
Conversion makes a converted copy. In balance = float (count), count keeps its own value and type.
Without conversion, + joins the strings: if both inputs are "3" and "4", the ‘total’ is "34".
If the user types ten when the program does int (input (…)), the program crashes with a ValueError. Checking input before converting it is validation (see the strings, files and validation topic).
Write clear prompts that say what to type and in what units, ending with a space: "Weight in kg: ".
Code
Result
Notes
int ("42")
42
String to integer
float ("2.5")
2.5
String to real
int ("2.5")
ValueError
int () can’t convert a string with a decimal point
int (7.9)
7
A real converted to an integer loses its fraction (no rounding)
str (3.0)
"3.0"
Number to string, ready to join to other strings
bool ("")
False
An empty string converts to False
bool ("No")
True
Any non-empty string converts to True, even "No" or "False"
Convert the input before using it as a number
Worked exampleThe user types 12 and then 8. What does each program output?
# Program A
first = input ("First: ")
second = input ("Second: ")
print (first + second)
# Program B
first = int (input ("First: "))
second = int (input ("Second: "))
print (first + second)
Program A: both are strings, so + joins theminput () always returns a string
Program B: both are integers, so + adds themint () converted each input
Program A outputs 128. Program B outputs 20.
Exam tipRead the task for the type it wants. ‘Take a decimal input’ needs float (). Using int () crashes when the user types 2.5.
Conversion (casting)
Changing a value from one data type to another with int (), float (), str () or bool ().
ValueError
The runtime error when a value can’t be converted, e.g. int ("ten").
Edexcel 1CP2 · 6.5.1
Arithmetic operators and rounding
/ always gives a real: 8 / 2 is 4.0, not 4.
// and % go together: 17 eggs in boxes of 5 is 17 // 5 = 3 full boxes and 17 % 5 = 2 eggs left over.
number % 2 == 0 is True for even numbers. number % 10 gives the last digit.
Order of operations is BIDMAS: brackets, indices (**), division and multiplication, then addition and subtraction. Add brackets to make the order clear.
round (x, n) rounds to n decimal places, and round (x) to a whole number. Watch out: Python rounds an exact half to the nearest even number, so round (2.5) is 2.
Round only what you display. Keep the full value in the variable if it’s used again later, or format the output instead (see Output).
Operator
Meaning
Example
Result
+
Addition
17 + 5
22
-
Subtraction
17 - 5
12
*
Multiplication
17 * 5
85
/
Division (always gives a real)
17 / 5
3.4
//
Integer division (whole part only)
17 // 5
3
%
Modulus (remainder)
17 % 5
2
**
Exponentiation (power)
2 ** 5
32
Worked exampleA program has minutes = 200. Write expressions for the whole hours and the minutes left over, then evaluate 3 + 4 * 2 ** 2.
hours = minutes // 60 → 3how many whole 60s fit into 200
leftOver = minutes % 60 → 20200 − 3 × 60 = 20
2 ** 2 = 4 first, then 4 * 4 = 16, then 3 + 16BIDMAS: indices, then multiplication, then addition
3 hours 20 minutes; 3 + 4 * 2 ** 2 is 19.
Exam tipRounding the stored value instead of just the displayed one cost marks in 2023. Store the full result; round or format it only when you print it.
Integer division (//)
Divides and keeps only the whole-number part: 17 // 5 is 3.
Modulus (%)
The remainder after integer division: 17 % 5 is 2.
Exponentiation (**)
Raising to a power: 2 ** 5 is 32.
BIDMAS
The order of operations: brackets, indices, division and multiplication, addition and subtraction.
Edexcel 1CP2 · 6.5.2, 6.5.3
Relational and logical operators
Relational and logical operators make conditions. A condition is always True or False. Conditions control if and while (next topic).
Put brackets round each test and round the whole condition, Pearson’s way: if ((age >= 11) and (age <= 16)):.
A value inside a range needs and: (mark >= 0) and (mark <= 50). A value outside a range needs or: (mark < 0) or (mark > 50).
Check the boundaries. ‘From 1 to 20’ includes 1 and 20, so use >= and <=. ‘Over 18’ means > 18.
You can store a condition’s result in a Boolean variable: isTeenager = (age >= 13) and (age <= 19).
Strings are compared by their character codes, so "Zara" < "amir" is True: every capital letter comes before every lower-case letter. Compare whole strings with ==.
Relational operator
Meaning
Example (age = 15)
Result
==
equal to
age == 15
True
!=
not equal to
age != 15
False
>
greater than
age > 15
False
>=
greater than or equal to
age >= 15
True
<
less than
age < 18
True
<=
less than or equal to
age <= 11
False
Logical operator
Result is True when…
Example (age = 15)
Result
and
both sides are True
(age >= 11) and (age <= 16)
True
or
either side is True (or both)
(age < 5) or (age > 65)
False
not
the condition is False (it inverts it)
not (age >= 18)
True
Worked exampletemp = 24 and raining = False. Evaluate: (a) (temp > 20) and (not raining) (b) (temp < 5) or raining (c) not ((temp >= 18) and (temp <= 24))
(a) True and True → True24 > 20 is True; not False is True
(b) False or False → False24 < 5 is False and raining is False
(c) not (True and True) → not True → False24 is inside 18 to 24 inclusive, then not inverts it
(a) True (b) False (c) False
Exam tipRange checks are where examiners see the most relational-operator mistakes: > where >= was needed, or and where or was needed. Test with the boundary values themselves.
Relational operator
Compares two values: ==, !=, >, >=, <, <=. The result is True or False.
Logical operator
Combines or inverts conditions: and, or, not.
Condition
An expression that is either True or False.
Edexcel 1CP2 · 6.4.1
Output: print, concatenation and .format()
print ("Total:", total): commas separate items and add a space between them. Items can be any type.
+concatenates (joins) strings with no space added. Numbers must be converted first: print ("Total: " + str (total)). Without str () you get a TypeError.
Don’t join strings with commas outside print. line = "Total:", total makes a tuple, not a string, and examiners penalise it.
"=" * 20 gives a line of 20 equals signs. "\n" inside a string starts a new line.
.format () puts values into placeholders { } in a string, in order. Inside a placeholder: alignment (< left, > right, ^ centre), width, precision (.2) and type (s string, d integer, f fixed-point real).
Store a layout string once and reuse it so the columns line up: layout = "{:<10}{:>8.2f}", then print (layout.format (item, price)).
.format () rounds what is shown. The variable keeps its full value.
f-strings (f"{price:.2f}") aren’t in the PLS, but you may use them unless the question says to use .format ().
Code
Output (· shows a space)
"{:.2f}".format (3.14159)
3.14
"{:>8.2f}".format (3.14159)
····3.14
"{:<6}|".format ("Kit")
Kit···|
"{:^7}|".format ("Kit")
··Kit··|
"{:5d}".format (42)
···42
"{} scored {}".format ("Ali", 18)
Ali·scored·18
Each part of a placeholder is optional, but they always come in this order
Worked exampleWrite code to display this receipt, with item names left-aligned in 10 characters and prices right-aligned in 7 characters to 2 decimal places.
Tea 1.80
Flapjack 2.35
=================
Total 4.15
layout = "{:<10}{:>7.2f}"10 + 7 = 17 characters per line
print (layout.format ("Tea", 1.80)) and the same for Flapjackthe same layout keeps the columns lined up
Exam tipIf the paper says ‘use the <string>.format() function’, an f-string or round () won’t get that mark. The format is in the PLS, so check the placeholder order there.
Concatenation
Joining strings end to end with +.
Placeholder
A { } in a string that .format () fills with a value, e.g. {:>8.2f}.
TypeError
The runtime error when an operation is used on the wrong type, e.g. "Total: " + 5.
Edexcel 1CP2 · 6.2.1
Paper 2 skill: name the parts of a program
A ‘name the part’ question gives you a working program and a table of comments to fill in: a name in some rows, a line number in others.
Give exactly what the row asks for: a line number or a name. A name where a line number is needed scores nothing.
Give one answer per row. Only the first answer is marked.
The PLS on your desk has the words (constant, initialisation, iteration…) with examples. Use it to check.
Asked for
What to look for
Example
A constant
A name in CAPITALS given a value once, at the top
MAX_SEATS = 52
An initialisation
The first line that gives a variable a value
total = 0.0
An assignment
Any line that sets or changes a variable with =
total = total + cost
An input
A line using input ()
name = input ("Name: ")
A conversion
int (), float (), str () or bool () round a value
float (input (…))
An arithmetic expression
+ - * / // % ** used on numbers
cost * QUANTITY
A relational or logical test
== != > >= < <=, and, or, not
(age > 4) and (age < 12)
An output
A line using print ()
print ("Done")
Selection, repetition, iteration
if/elif/else; while or for … in range; for … in a list
See the next topic
Worked exampleUsing the program below, give: (a) the name of a constant (b) the line number of an initialisation of a Boolean (c) the line number of a conversion to an integer (d) the line number of an output.