Example questions are derived from past papers.
For each paper 2 - 15 mark question, you’ll notice there’s always a list of requirements for you to complete. This cheatsheet is designed to help you with these requirements by providing short snippets of the typical requirements you will need to complete in the past paper.
DISCLAIMER: The terms
single variable inputsandmultiple variable inputsare not official terms, but rather terms I have used to describe the different types of inputs you may need to collect as typically seen in past papers.
This is essentially when you have to input specific variables all of which unique in their own way. For example, if you need to input their name, age, or even things like temperature. If you need to input multiple values, see Multiple Variable Inputs.
# INPUTTING
variable = input("Please enter the ... : ")
Note that for
floatorintinputs, you would usefloat(input("..."))orint(input("..."))respectively. Remember that afloatis a decimal number, whereas anintis a whole number.
Question derived from this past paper.
Question = input a new customer’s name, room length and room width
# INPUTTING
Name = input("Please enter the customer's name: ")
RoomLength = float(input("Please enter the room's length: "))
RoomWidth = float(input("Please enter the room's width: "))
For this example, the RoomLength and RoomWidth are float inputs because they are decimal numbers. As the input("...") function will give back (return) a string, we need to convert it to a float using float(input("...")).
This is for when you have to input multiple bits of data which are of the same type. For example, if you had to store the different goals in a football match, each goal would be stored in the list/array named goals. Another example is if you had to store all the different temperatures within an hour. Each separate temperature is stored in the array/list temperature
As there are multiple values, we should use an array (also known as a list) to store these values.
# INPUTTING
for i in range(0, totalInputs):
inputs = input("Please enter the ... : ")
# If required, validation goes here
Note that here in the template totalInputs is a number (an integer) which is what you would put instead. It should be the total amount of numbers you need to collect. This is usually specified in the question.
Also note that if necessary, you can convert/cast the input to a float or int using float(input("...")) or int(input("...")) respectively.
Question derived from this past paper.
Question = input and validate the hourly temperatures for one week
For this question, I will choose to ignore the validation point for later, as it requires a different code snippet. Also note that the below code snippet is NOT the solution to the PAST PAPER but rather the solution to the QUESTION based on how it’s worded. The solution to the past paper requires the for loop to run 24 times instead, as you need to check the hourly temperatures per day. However due to the background knowledge/context required meaning you have to read the full question I have chosen to ignore this and read the question without the context.
Note that for this question we need multiple temperatures as indicated by the plural temperatures. This means we need to store these temperatures in an array (also known as a list). But as temperatures are not a string, we should also convert the input into a float using float(input("...")).
# INPUTTING
temperatures = [] # List to store the temperatures
for i in range(0, 7): # 7 days in a week
temperature = float(input("Please enter the temperature for today: "))
# Validation goes here
temperatures.append(temperature) # Add the temperature to the list
The variable temperature is only used to temporarily store the temperature input. Once the temperature is stored, it is added to the list temperatures using the append function. This is to basically store the value, as if we did not have a list to store the temperatures, we would not be able to access them later. At each iteration, (meaning at each time the loop runs) the temperature value is overwritten/changed to the new temperature input, meaning its value is constantly changing, therefore we need to store it in a list to access it later.
As the past paper questions may require you to validate your input (for example this past paper requires you to input and validate) I have included a section on input validation. However, I have noticed that range checks are most common, so I would highly recommend remembering at the minimum how to perform a range check.
As there are different types of input validation, I have included the following:
A range check is basically when you check if a number is within range. This is usually specified by the context provided for the 15 marker. For example, if you had to input the seat number in a booking system, you may have to check if the seat number is within the range of 1 to 100 as there are only a limited amount of seats.
Note that if a question ever specifies that the range is inclusive, it means that it includes the values at the start and end of the range. For example, if the range is
1to100, it means that1and100are included in the range. If the range is exclusive, it means that it does not include the values at the start and end of the range. For example, if the range is1to100, it means that1and100are not included in the range, so it only goes from2to99
As a while loop will run while the statement/condition inside of it is true, and as we need to keep asking the user for input until they give us a valid input, we will be using the not keyword to check if the input is not within the range. This is because if the input is not within the range, the condition will be true and the while loop will run. (It will ask for the user to re-enter their value if the input is wrong) If the input is within the range, the condition will be false and the while loop will not run at all.
# Validation - Range Checks
while not(lowerBound < value < upperBound): # For exclusive, use <= for inclusive
print("Invalid input, please try again, but make sure to enter the value within the range lowerBound to upperBound.") # Error message
value = float(input("Please enter the ... : ")) # Re-enter value
Please note that lowerBound < value < upperBound is the exact as saying value > lowerBound and value < upperBound. Using the simple method of lowerBound < value < upperBound is just a shorthand way of writing the same thing and is also accepted in the exam.
Also note that the not() function (exactly like the logic gate) will flip the condition within it. Meaning if the condition inside of the brackets are True, they would flip to be False. And vice versa. This is why we use not() to check if the value is not within the range, as if it is not within the range, the condition will be True, and the while loop will run.
Question derived from this past paper.
Question = input and validate the hourly temperatures for one week
For this question, I will be assuming that the user has not yet inputted their values (check out the Multiple Variable Inputs section for the full code snippet).
Please note (as context) that the question also states the following:
Temperatures can only be from –20.0 °C to +50.0 °C inclusive.
As the temperature range is inclusive, we will use <= instead of < in the range check.
# Inputting code here...
# VALIDATION - Range Check
while not(-20.0 <= temperature <= 50.0):
print("Invalid input, please try again, but make sure to enter the temperature within the range -20.0 to 50.0.")
temperature = float(input("Please enter the temperature for today: "))
This code will run until the user enters a temperature within the desired/specified range.
To ensure that an input is not empty, you can use a presence check. This is useful when you need to make sure the user has entered some data and hasn’t left the input blank.
# Validation - Presence Check
value = input("Please enter the ... : ")
while value == "":
print("This field cannot be left blank. Please enter a value.")
value = input("Please enter the ... : ")
A format check ensures that the input matches a specific format, such as a phone number or email address. The best way to do so is to manually check (by getting specific index numbers) the input to see if it matches the desired format.
# Validation - Format Check
value = input("Please enter the ... : ")
while not(value[0] == "0" and value[1] == "7" and len(value) == 11): # Example for a UK phone number
print("Invalid format. Please try again.")
value = input("Please enter the ... : ")
Here, as an example, we are checking if the first two characters of the input are 0 and 7 respectively, and if the length of the input is 11. If the input does not match this format, the while loop will run, and the user will be asked to re-enter their value. As the first two characters of a UK phone number are 07 and the length is 11, this is a valid UK phone number format.
A type check confirms that the input is of the correct data type, such as an integer or string.
# Validation - Type Check
value = input("Please enter the ... : ")
while True:
try:
value = int(value) # Attempt to convert to the desired type, e.g., int
except ValueError:
print("Invalid type. Please enter a number.")
value = input("Please enter the ... : ")
break
The try and except blocks are used to catch any errors that may occur when trying to convert the input to the desired type. If an error occurs, for example if you tried to convert "Hello There!" into an integer, instead of ending the program, the code in the except block will run. If the input cannot be converted to the desired type, a ValueError will be raised, and the code inside the except block will run. In this case, it will print an error message, gather the user’s input, then break. break essentially stops the while loop from running anymore, and as the condition inside of the while loop is set to True, it will run infinitely (forever) until the code runs the break keyword.
A length check ensures that the input meets a certain length requirement, useful for inputs like usernames or passwords.
# Validation - Length Check
value = input("Please enter the ... : ")
min_length = 0 # Minimum length
max_length = 0 # Maximum length
while not (min_length <= len(value) <= max_length):
print(f"Input must be between {min_length} and {max_length} characters long.")
value = input("Please enter the ... : ")
Basically the len() function is used to get the length of the input. If the length of the input is not within the specified range, the while loop will run, and the user will be asked to re-enter their value. The range min_length <= len(value) <= max_length will do the same as min_length <= len(value) and len(value) <= max_length. This is just a shorthand way of writing the same thing. The reason why we use not is because if the length of the input is not within the range, the condition will be True, and the while loop will run, and the while loop only runs while the input is not valid as it needs to re-enter the input.
For loops are used for iterating over a sequence (such as a list, tuple, or string) or other iterable objects.
# For Loop
for i in range(start, end): # start is inclusive, end is exclusive
# Your code here
While loops repeat as long as a certain boolean condition is met.
# While Loop
while condition:
# Your code here
Python does not directly support do-while loops, but you can simulate one using a while loop.
# Do While Loop Simulation
while True:
# Your code here
if condition_to_exit: # condition to exit the loop
break
To calculate the average of a set of numbers, you sum all the elements and then divide by the number of elements.
# Average Calculation
numbers = [] # This should be a list of numbers
total = sum(numbers) # Sum all the elements in the list
average = total / len(numbers) if numbers else 0 # Calculate the average
print(f"The average is: {average}")
Summation involves adding up a sequence of numbers.
# Summation Calculation
numbers = [] # This should be a list of numbers
total_sum = sum(numbers)
print(f"The total sum is: {total_sum}")
Calculating the maximum and minimum values from a list of numbers.
# Maximum Calculation
numbers = [] # This should be a list of numbers
max_value = max(numbers)
print(f"The maximum value is: {max_value}")
# Minimum Calculation
numbers = [] # This should be a list of numbers
min_value = min(numbers)
print(f"The minimum value is: {min_value}")
Functions are defined to perform a specific task and can return a value.
# Function Definition
def function_name(parameters):
# Your code here
return result
# Function Call
result = function_name(arguments)
print(result)
In Python, a procedure can be considered a function that does not return a value.
# Procedure Definition
def procedure_name(parameters):
# Your code here
# No return statement needed
# Procedure Call
procedure_name(arguments)
Iterating over a 2D array involves nested loops to access each element.
# 2D Array Iteration
array_2d = [] # This should be a 2D list (a list of lists)
for row in array_2d:
for element in row:
print(element)
As this is still a work in progress, feel free to view the roadmap here to check for future updates.
If you have any features you would like to suggest, or notice any issues with the website, please submit an issue on Github.
If you like my work, consider supporting me by following me on GitHub, or check out my personal website!