A whole number
A decimal number
A single character in quote marks ("A")
Multiple characters in quote marks ("Hello")
True or False
Note: Python does not have characters as a data type and just treats them as strings
Store data that can be accessed within the code.
Can be entered by programmer or by user
Can change whilst program is running
Store data that can be accessed within the code.
Usually set by the programmer
Can't change whilst program is running, meaning it stays the same throughout
Below is a python program that calculates the VAT of a purchase in a shop.
The VAT is 20% so this is a constant (you can tell by it being in capitals)
The order is a variable as the user is entering the cost of each order
The total is a variable as it calculates the total cost of the order + VAT for each order
VAT = 0.2
order = float(input("Enter cost of the order: "))
total = order + (order * VAT)
print(f"your total cost including VAT is: £{total}")
inputs are used to allow the user of the program to type in data, usually in response to a question asked by the program.
name = input("Please enter your name: ")
outputs are used to show data to the user from within the program, usually the result of something the user has asked for or the program is built to do.
in the input section, we get the user to enter their name, let's output a welcome message that is personalised to them. (the user typed in John Connor
print(f"Welcome {name}!")
would show the user:
>> Welcome John Connor!
With integers and floats you can perform arithmetic (mathematical) operations.
Addition is carried out with the + symbol
num1 = 13
num2 = 18
print(num1 + num2)
would output
>> 31
Subtraction is carried out with the - symbol
num1 = 18
num2 = 13
print(num1 - num2)
would output
>> 5
Multiplication is carried out with the * symbol
num1 = 3
num2 = 8
print(num1 * num2)
would output
>> 24
Exponent means the power of, for example 5 to the power of 2 = 25
Exponent is carried out with **
num1 = 3
num2 = 8
print(num1 ** num2)
would output
>> 512
Division is carried out with the / symbol
num1 = 17
num2 = 2
print(num1 / num2)
would output
>> 8.5
Integer Division returns the whole number result of a division
Integer Division is carried out with //
num1 = 17
num2 = 2
print(num1 // num2)
would output
>> 8
Remainder Division returns the remainder result of a division
Remainder Division is carried out with %
num1 = 17
num2 = 2
print(num1 % num2)
would output
>> 1
num1 = 3
num2 = 5
if num1 < num2:
print("num2 is bigger")
else:
print("num1 is bigger")
num1 = 3
num2 = 5
if num1 > num2:
print("num1 is bigger")
else:
print("num2 is bigger")
age = 18
if age <= 17:
print("you are legally a child")
else:
print("you are legally an adult")
age = 18
if age >= 18:
print("you are legally an adult")
else:
print("you are legally a child")
password = "abc123"
user_pwd = input("Enter password: ")
if user_pwd == password:
print("access granted")
else:
print("incorrect password")
password = "abc123"
user_pwd = input("Enter password: ")
if user_pwd != password:
print("incorrect password")
else:
print("access granted")
if weather == "sunny" and temperature >= 20:
print("picnic!")
else:
print("eat inside")
if weather == "sunny" or temperature >= 20:
print("ice cream")
else:
print("cake")
found = False
if not found:
print("not found")
else:
print("found")
In Python, all inputs are strings, but sometimes, you need the user to be able to input a whole number or a decimal number, to do this, we need to do something called type casting.
To do this, Python has a couple of built-in functions that take the string and turn it into a integer or a float (decimal).
num = int(input("Enter a number: "))
it is important to recognise that the int() function has its own brackets and so does the input() function, therefore you put the input inside the brackets for the int() function.
num = float(input("Enter a decimal: "))
Just like the int() function, the float() function has its own brackets.
It is also possible to turn integers and floats into strings using a built-in function.
print(str(num))
in this example, the print() function has its own brackets and so does the str() function, however, unlike our inputs above that went inside the int() and float() functions, this time we are outputting the string version of num and therefore, the print() goes on the outside.
Strings are a sequence of characters enclosed in quote marks, because of this, we can manipulate them to access each individual letter. Python has a few built-in functions that are used to manipulate strings.
To find the length of a string, Python has a function called len().
animal = "hippopotamus"
print(len(animal))
will return:
>> 12
It is important to note that if there is more than 1 word in the string, the spaces will be counted too.
A substring is a set of characters within a string.
To do this in python, we give the name of the string followed by square brackets we then give a start index, an end index and a step (optional).
format:
string[start:stop:step]
for example:
word = "Computer Science"
print(word[3:5])
would output
>> put
Notice, we didn't use the step value here, it is optional and we didn't need it, however, you could do this:
print(word[::2])
would output every other letter in Computer Science
>> Cmue cec
To find the position of a letter or substring in a string, we use the index() function.
To do this in python, we give the name of the string followed by .index() but inside the brackets we need to put the character or substring we are looking for.
Optionally, you can also give index() a start and end of you want to look for a particular value within a certain range of text.
format:
string.index(value, start, end)
for example:
word = "Computer Science"
print(word.index("put"))
would output
>> 3
because the word put starts at index 3 in the word Computer.
In Unit 3 (Data Representation), you will learn about ASCII, it stands for American Standard Code for Information Interchange. basically, it is an agreed upon format for storing the keys on the keyboard on the computer using binary so that the computer knows which letter you pressed.
Python has a couple of built-in functions that allow us to convert a letter to its ASCII number and vice versa.
To convert a letter to ASCII in Python, we use the ord() function.
letter = "A"
print(ord(letter))
would output
>> 65
To convert the ASCII value to the letter in Python, we use the chr() function.
ASCII_val = 66
print(chr(ASCII_val))
would output
>> B
You will have noticed that A gave us 65 and 66 gave us B, this is because there are other buttons on the keyboard that have to be stored so we get to the alphabet at 65 for capital A all the way to capital Z at 90 and then lowercase a starts at 97 and lowercase z is 122.
To find out what these are as binary, you can use the bin() function
letter = "A"
ASCII = ord(letter)
binary = bin(ASCII)
print(binary)
would output
>> 01000001
Concatenation is joining together two or more strings. In python, this is done using the + operator.
for example:
firstname = "John"
surname = "Connor"
fullname = firstname + " " + surname
print("Hello" + " " + fullname)
would output
>> Hello John Connor
Notice, when joining strings together using concatenation, you must also join a space between them, otherwise it will join them together like this:
firstname = "John"
surname = "Connor"
fullname = firstname + surname
print("Hello" + fullname)
>> HelloJohnConnor
A set of events, actions, numbers, etc. which have a particular order and lead to a particular result.
Example:
Here are the instructions to a morning routine:
Get dressed
Brush teeth
Have breakfast
Make the bed
Get out of bed
Have a shower
The order in which tasks are done here do not make sense, how can you make the bed before you get out of it, likewise why would you get dressed and then have a shower or brush your teeth before you have had breakfast. It may make more sense to do it in this order:
Get out of bed
Make the bed
Have a shower
Get dressed
Have breakfast
Brush Teeth
The same principle applies in programming, each instruction is carried out one after the other. So they need to be a logical order for the computer to be able to run the program successfully.
All programs have a series of steps to be followed In sequence. Here is an example in which the steps are simple assignment statements:
score1 = int(input("Enter score for Round 1: "))
score2 = int(input("Enter score for Round 2: "))
average = (score1 + score2) / 2
print(f"The average score is: {average}")
Deciding what comes next based on the meeting of a condition.
Example:
Imagine a game of guess who, 2 players, each player has a person that they "are".
They then take it in turns to ask questions like "Does your person wear glasses?"
If your person does wear glasses, you say "yes" and they get rid of all possible people without glasses.
Else, you say "no" and they get rid of all possible people with glasses.
The same principle applies in programming, you ask the user a question and depending upon what they say, you tell the program to take a specific course of action.
Here is an example of guess who implemented in Python:
answer = input("Does your person wear glasses? ")
if answer == "yes":
wearsGlasses = True
else:
wearsGlasses = False
Repeating until an amount or condition is met.
Example:
If I said to you: "say hello 5 times"
you would go: "hello, hello, hello, hello, hello"
but in your brain, as you have said each of those hello's you have gone 1,2,3,4,5.
This is a for loop, for each number in this amount of times, do this.
Alternatively, I could say to you: "while you are doing your GCSE in Computer Science, say hello" and then who knows how many times you will say the word hello for 2 years straight without stopping.
This is a while loop, while something is the case, do this.
So, there are 2 types of iteration:
Definite iteration - a count-controlled loop that will definitely run and we know how many times it will run (finite) - For loop.
example:
total = 0
scores = int(input("How many scores would you like to enter? "))
for score in range(scores):
newScore = int(input("Enter Score: "))
total = total + newScore
Indefinite iteration - a condition controlled loop that may never run, may run a number of times we don't know or may run forever (infinite) - While loop.
example:
total = 0
loop = True
while loop == True:
scores = input("Do you have more scores to enter? "))
if scores == "yes":
newScore = int(input("Enter Score: "))
total = total + newScore
else:
loop = False
It is also possible to have loops nested inside other loops, this is most commonly done with for loops.
Here is an example in Python that will output the times tables between 2 and 12 to 12 x the table value.
for table in range(2,12):
for count in range(1,12):
print(f"{table} x {count} = {table x count}")
Here is a snippet of the output (the ... show where outputs have been hidden.)
>> 2 x 1 = 2
>> 2 x 2 = 4
>> 2 x 3 = 6
>> 2 x 4 = 8
>> 2 x 5 = 10
...
>> 10 x 12 = 120
...
As we discussed earlier, variables are used to store data, the data we looked at previously was a single piece of data:
name = "John"
but sometimes, we want to store multiple pieces of data in a single variable, this is where arrays come in, they allow us to store multiple pieces of data into a single variable by making them a list. Arrays use square brackets [] to contain the list.
names = ["John", "Sarah" , "Kate"]
We can then output the entire list by using:
print(names)
>> ["John", "Sarah", "Kate"]
if you want to output a single item from the list, you must use its index. Indexing of an array talks about an items position in the list, for example, in a shopping list used by humans:
Bread
Milk
Cheese
Bread is item 1, Milk is item 2 and Cheese is item 3.
In arrays, the first item is item 0.
shopping_list = ["Bread", "Milk", "Cheese"]
Bread is item 0, Milk is item 1 and Cheese is item 2. To output each individual item, you must put the items index in square brackets, like so:
shopping_list = ["Bread", "Milk", "Cheese"]
print(shopping_list[1])
would return:
>> Milk
we may want to output every item in the list like this, to do this, we need to use iteration, because we know how long the array is, we use definite iteration (for loop)
shopping_list = ["Bread", "milk", "Cheese"]
for item in shopping_list:
print(shopping_list[item]
will output:
>> Bread
>> Milk
>> Cheese
as well as outputting from an array, we can also add to them, just like how we can add to a shopping list. To do this, we use the append() function, this adds the data to the end of the list.
example:
shopping_list = ["Bread", "Milk", "Cheese"]
shopping_list.append("Potatoes")
will become:
shopping_list = ["Bread", "Milk", "Cheese", "Potatoes"]
arrays are also capable of storing pther arrays, when this happens, we refer to them as 2D arrays or 2-Dimensional Arrays.
2D arrays operate in a row then column format with indicies in their own square brackets.
example:
0 1 2 3 4
hotel = [["O","O","V","O","V"], <- Array 0
["V","O","V","O","V"]] <- Array 1
To access the data, you use the name of the array and then the index of the row, followed by the index of the column. For example:
print(hotel[0][2])
will output
>> V
because in array 0, position 2 there is a V.
Records are a data structure used to store multiple items of data about one "thing", all together. for example, a contact in an address book.
Creating the structure of a record:
RECORD Contact
name: string
phone: string
address: string
postcode: string
favourite: boolean
ENDRECORD
here, Contact is the name of the record, name, phone, address, postcode and favourite are known as attributes and the string and boolean are the data types for the attributes.
To create a new record, we need to use the records name and then give it data for each attribute in the correct order.
example:
Terry = Contact("Terry", "07987654321", "Tracyes Road", "CM18 6JH", True)
To access the data from a record later, we print the name of the individual and the attribute we want.
for example:
print(Terry.phone)
print(Terry.postcode)
will return:
>> 07987654321
>> CM18 6JH
now, lets imagine Terry gets a new phone and moves house, we need to be able to change or update his data, with a record, this is really simple, you simply state the individual name, the attribute you want to chnage and the data to change it to. Like this:
Terry.phone = 07123456789
Terry.address = "Rundells"
A syntax error occurs when the spelling, punctuation or grammar of Python isn't correct in your code.
example:
age = int(input("Enter your age: ")
in this example, there is a brcket missing on the end because we have opened 2 brackets after int and input but only closed 1. It should be:
age = int(input("Enter your age: "))
This was an error with the punctuation.
A spelling error would be like this:
name = imput("Enter your name: ")
should be:
name = input("Enter your name: ")
A logic error occurs when there is a conflict in your statements in python.
example:
num1 = 5
num2 = 7
if num1 > num2 and num2 > num1:
print("num1 is bigger than num2 and num2 is bigger than num1")
it isn't possible for both numbers to be biggest. this is a logic error.
Boundary testing is where you test the boundaries of a users input.
example:
num = int(input("Enter a number between 1 and 10: "))
in this example, the user is asked to enter a number between 1 and 10 so the boundaries are 1 and 10.
Erroneous testing is where you test what happens if users input the wrog thing.
example:
num = int(input("Enter a number between 1 and 10: "))
in this example, the user is asked to enter a number between 1 and 10 so the erroneous data is 0 or less and 11 or more. It would also be any words (strings).
Normal testing is where you test that the user has input something you expect.
example:
num = int(input("Enter a number between 1 and 10: "))
in this example, the user is asked to enter a number between 1 and 10 so the normal data would be any number between 1 and 10.
Validation is when the programmer writes code to check that what the user has entered is valid. It does not check that what they have entered is correct but instead, checks that it meets certain requirements.
for example, if a user is asked to enter their name, the field cannot be left blank, checking that the field isnt blank is an example of validation.
There are 3 types of validation the specification requires you to know. Length Check, Presence Check and Range Check.
Length Check:
checks the length of the input meets requirements.
number = input("phone number: ")
while len(number) != 11:
print("number invalid")
number = input("phone number: ")
Presence Check:
checks the input is not left empty.
name = input("enter name: ")
while name == "":
print("name cannot be blank")
name = input("enter name: ")
Range Check:
checks the input is within a specified range.
num = int(input("enter number between 1 and 10: "))
while num not in range(1,11):
print("invalid number")
num = int(input("enter number between 1 and 10: "))
Verification is when the programmer writes code to verify that data is accurate. For example, when a person logs in, a username and password must be entered and checked against what is saved to ensure it matches. This then authenticates the user is who it should be.
For example:
username = "CS_Student"
password = "Aff5"
user = input("enter username: ")
pass = input("enter password: ")
if user == username and pass == password:
print("Welcome back", user)
width = int(input("Enter width: "))
height = int(input("Enter height: "))
area = width * height
print(area)
To determine the purpose of this algorithm, we analyse the inputs, the names of the variables, the processes taking place and the outputs.
for example
the inputs here are asking for a width and a height to be entered and these are being stored into variables called width and height as integers.
the process then shows the program multiplying the width by height and storing it in a variable called area.
the output then is the area variable.
from this, we can identify that the program is calculating the area of a shape.
As well as built-in functions, Python allows you to create your own custom functions and procedures, these are both known as subroutines.
Procedures and functions have 1 fundamental difference.
Procedures output their result to the user, functions return their result to the rest of the program so the result can be used further.
to create subroutines, we have to define them, like this:
def SubroutineName(parameter1, parameter2, ...):
Note: the parameters are optional, they are used to pass variables or values to the subroutine that it may need to calculate its result.
As mentioned above, procedures perform their task and then output their result to the user.
Here is an example of a procedure being used to calculate the area of a shape and output (print) the result on screen.
def AreaCalculator(height, width):
area = height * width
print(area)
To use the procedure, you have to call it within the sequence of your program.
example:
height = int(input("Enter height: "))
width = int(input("Enter width: "))
AreaCalculator(height, width)
The result of AreaCalculator will be output on the screen as per line 2 of the procedure.
As mentioned above, functions perform their task and then return their result to the rest of the program for further use.
Here is an example of a function being used to calculate the area of a shape and return the result to the program.
def AreaCalculator(height, width):
area = height * width
return area
To use the function, you have to call it within the sequence of your program.
example:
height = int(input("Enter height: "))
width = int(input("Enter width: "))
AreaCalculator(height, width)
The result of AreaCalculator will not be output on the screen. To do this we need to modify the program like this:
height = int(input("Enter height: "))
width = int(input("Enter width: "))
print(AreaCalculator(height, width))
The value of functions is that if you want to do anything with the result, you can whereas, this isn't possible with procedures as they have already output the result to the user and not given it back to the program.
for example:
def AreaCalculator(height, width):
area = height * width
return area
height = int(input("Enter height: "))
width = int(input("Enter width: "))
if AreaCalculator(height, width) > 250:
print("The area of this shape is greater than 250")
else:
print("The area of this shape is under 250")
This wouldn't be possible using a procedure.
Using subroutines to perform specific tasks in a program has many advantages:
Breaking down or decomposing a large problem into sub-tasks, and writing each of these as a subroutine, makes the problem easier to solve
Each subroutine can be tested separately
Subroutines can be used several times within a program
Subroutines can be stored in a subroutine library and used in different programs if needed
Several programmers can work on a large program at the same time, writing different subroutines, so a large job will get done more quickly
If the requirements of a problem change, it is much easier just to make a change in a subroutine than to search through a long program to find what lines need changing, so program maintenance is easier.
A structured programming approach is one which has the following characteristics:
It uses a modularised approach. This means it uses subroutines to break down the program into manageable chunks of code. Each subroutine should have a clear, well documented interface (parameters and return value)
It uses only the constructs of sequence, selection and iteration.
Note that the term subroutine interface refers to the number, type and order of the parameters that appear in the subroutine header, and the type of the return value.
Breaking down or decomposing a large problem into sub-tasks, and writing each of these as a subroutine, makes the problem easier to solve
Each subroutine can be tested separately
Subroutines can be used several times within a program
Subroutines can be stored in a subroutine library and used in different programs if needed
Several programmers can work on a large program at the same time, writing different subroutines, so a large job will get done more quickly
If the requirements of a problem change, it is much easier just to make a change in a subroutine than to search through a long program to find what lines need changing, so program maintenance is easier.
The use of just three or four programming structures makes a program relatively easy to understand, debug and maintain.
A global variable is one which is declared in the main program and is recognised in all the subroutines called from the main program.
Functions and procedures may use their own variables which are not known about or recognised outside the subroutine. In the function above which calculates the area, area is a local variable, declared within the subroutine and only existing while the function is being executed. It is not recognised anywhere else in the program.
When a function or procedure is executed, it will automatically use the variables found locally, even if there is a global variable with the same name. If the variable is not found locally it will use the global variable. This means that the same variable identifiers can be used in several different procedures. This is useful if different people are writing different sections of the program.
Using local variables in a subroutine is good practice because it keeps the subroutine self-contained. The subroutine can be used in any program and there will be no confusion over which variable names in the main program might conflict with names used in a subroutine.
This also leads to the further advantage that the program will be easier to debug and maintain.
If memory space is an issue, the use of local variables will save on memory as the space used by local variables is freed up when the subroutine completes.
Using local variables in a subroutine is a form of abstraction. The user of the subroutine needs only to know what inputs to the subroutine are required, and what the output will be. The detail of how the subroutine works and the variables it uses are hidden.
The following function returns the average of three numbers num1, num2, and num3.
def Average(num1,num2,num3):
total = num1 + num2 + num3
average = total / 3
return average
The function could be called using the statement
mean = Average(n1,n2,n3)
The return value, a local variable named average in the subroutine, will be passed to mean in the calling routine.
The variable total is also a local variable inside the function Average. If you try to print it outside the function, you will get an error message.
As well as built-in and custom functions, Python allows you to import functions from other banks of Python code, these are called libraries.
One such library is the random library, where there are functions that allow us to randomly choose between options or randomly generate numbers.
To make use of these functions, you have to tell your Python program to import the random library, this is done like this:
import random
The randint funtion is a part of the random library that allows us to generate random whole numbers (int being integer). The function takes 2 arguments, the lowest number you would like it to consider and the highest.
Here is an example of a basic number guessing game using randint to randomly pick the number to guess:
import random
rand_num = random.randint(1,100)
guess = int(input("Enter your guess: "))
if guess == rand_num:
print("you guessed it!")
else:
print("nope")
The choice function is a part of the random library and allows us to randomly pick an option from a set of options.
Here is an example of a basic word guessing game using choice to randomly pick the word to guess:
import random
words = ["apple","grape","pear"]
rand_word = random.choice(words)
if guess == rand_word:
print("you guessed it!")
else:
print("nope")