Key Syntax

Below is a summary of the key commands you may need in your controlled assessment as well as examples of them being used:

Command Description Example of Use
print()
Used to output text to screen
print("Hello World")
If you wish to join a string to a variable, you can use a + or a , like below:
name = “Bob”
print(“Hello “ + name)
print(“Hello”,name)
input()
Used to take input from a user, if you wish to store this input you need to assign it to a variable
input(“What is your name”)
If you want to assign to a variable, it needs to be:
variableName = input(“Text to display”)
\n
Creates a new line inside a print command.
print(“This is line 1 \nThis is line 2”)
print(“Name: “ + name + “\nAge:” + age)
NOTE: The \n must always be inside quote marks
str()
Converts a variable to a string, should be used in a print command to convert a variable that is not a string back to a string
str(variableName)
If used in a print command:
total = number1 + number2
print(“The total is “ + str(total))
int()
Converts a variable to an integer.
int(variableName)
For example:
total = int(number1) + int(number2)
float()
Converts a variable to a real number.
float(variableName)
For example:
total = float(number1) + float(number2)
round()
Rounds a variable to the number of decimal places specified.
round(variableName,dp)
where dp is the number of decimal places.
For example:
total = float(round(number1,2))
if condition:
   DO IF TRUE
else:
   DO IF FALSE
An IF statement which checks a condition and then does one of two things
if age==15:
   print(“You can go to the party”)
else:
   print(“You cannot go to the party”)
if condition:
   DO IF TRUE
elif condition:
   DO IF TRUE
else:
   DO IF FALSE
An if statement that makes use of elif to check two conditions, it will do one thing if the first condition is true, something else if the second condition is true, and if neither are two will do the false part.
if number1>number2:
   print(“Number 1 is bigger”)
elif number2>number1:
   print(“Number 2 is bigger”)
else:
   print(“The numbers are the same”)
for x in range(a,b):
   code to loop
code to execute after the loop
This is a for loop that will repeat the code inside of it a set number of times. A is the number at which the loop starts, B is the number at which the loop ends.
for x in range(0,10):
   number = int(input(“Enter a number”))
   total  = total + number
This program will loop ten times. Inside the loop each time it will ask for a number and add to the total.
NOTE: The indent
while CONDITION TRUE:
   code to loop
code to execute after the loop
This is a while loop that will repeat the code inside of it while a condition is met. The condition can be anything you want.
while age<18:
   age = int(input(“Please enter an age:”)
print(“You are old enough to see the film”)
This while loop will repeat while the age is less than 18. Every time the user enters an age if they enter a number less than 18 it will ask them again. When they enter an age over 18 it will then display the print command that comes after the loop.
ListName = list()
This will create a blank list with the name of your choice. A list can store multiple pieces of data under a single variable name.
names = list()
This will create a blank list called names that can then store multiple names when they are appended (added) to it.
ListName.append(data)
This will append the data that is in the brackets to the list. Append means add it to the list.
names = list()
names.append(“Bob”)
names.append(“Sally”)
print(names[1])
This code will create a blank list called names and then add the names Bob and Sally to it. The print command at the end would print Sally as lists start at zero. The second name in the list is Sally which would be stored in element 1.
NOTE: the square brackets for the element of the list.
ceil(number)
This function rounds up a number to the nearest whole number. This is part of the math library
from math import *
number = float(input(“Enter a decimal number”))
roundup = ceil(number)
print(roundup)
When using the ceil function you must import the math library, the first line of code at the top does this. This program takes a decimal input from the user, then uses ceil to round it up to the next whole number and then prints it. E.g. if the user entered 5.345 it would print 6.
variable = open(“filename”,”r”)
This will open a file in read mode.
file = open(“staff.csv”,”r”)
This will open a file called staff.csv in read mode with the variable name file.
variable = open(“filename”,”r”)
for line in file:
   DO THIS CODE
line 2 being explained
This will create a loop that will repeat for each line in the file.
file = open("staff.csv","r")
for line in file:
   print(line)
This will open a file called staff.csv in read mode and then read each line in the file. It will then print the line that it has read and repeat this until all lines have been read.
variable = open(“filename”,”r”)
for line in file:
   variable = line.split(“,”)
line 3 being explained
This will read a line from the file and split the contents of the line every time it finds a comma in a different element of the list/array.
file = open("staff.csv","r")
for line in file:
   details = line.split(",")
   print(details[0])
This will open a file called staff.csv in read mode and then loop through the file. Each time through the loop it will read a line and split the contents of the line every time it reaches a comma into a different element of the list/array. It will then print whatever is in element 0 of that array. i.e. the first piece of data before the first comma.
variable = open(“filename”,”r”)
for line in file:
   variable = line.split(“,”)
   if CONDITION:
      DO IF MET
line 4&5 being explained
An if can be used to check pieces of data stored in the list/array and see if it matches what you want. You can then program it to respond in a particular way if it does.
email = input("Enter the staff email address: ")
file = open("staff.csv","r")
for line in file:
   details = line.split(",")
   if details[2]==email:
      print(“Match found”)
This code will do what the previous code did, but check to see if what is in element 2 of the list/array details matches the email address entered by the user. If it does it will say “Match found”
variable.close()
This will close the variable that has created the connection to the file.
file = open("staff.csv","r")
file.close()
This will close the connection to the file that it has just opened.
variable = open(“filename”,”a”)
This will open a file in append mode.
writefile = open(“staff.csv”,”a”)
This will open a file called staff.csv in append mode with the variable name writefile. Append mode means ‘add’ to the file.
variable = open(“filename”,”r”)
variable.write(data to write)
line 2 being explained
This will write data to a file.
writefile = open("staff.csv","r")
writefile.write(“Bob” + “,” + “Barnes” + “,” +
 “Outwood Grange Academy”)
This will open a file called staff.csv in append mode. It will then write to the file the name of the staff member and the school they work at. You can also write variables to the file, like so:
firstname = input(“Enter your firstname “)
surname = input(“Enter your surname “)
school = input(“Enter your school “)
writefile = open("staff.csv","r")
writefile.write(firstname + “,” + surname + “,” + school)
NOTE: The use of a comma (,) to separate each piece of data
def functionname():
   CODE to run in function
This will define a function that has no values passed into it.
def hello():
   print(“Hello from a function”)
hello()
This code creates a function called hello. Inside that function it has some code that says to print a message. After the function, in the main program it is called by typing the name of the function followed by two brackets ().
def functioname(parameters):
   CODE to run in function
   return variable/value
This will define a function that has a parameter passed into it to be used in the function. It also has a return value. NOTE: With a function you do not have to have a return value.
def multiply(a,b):
   answer = a * b
   return answer

num1 = 10
num2 = 9
print(multiply(num1,num2))
This code creates a function called multiply and has 2 values passed into it that are referred to as a and b. Inside the function it multiplies to the two together and returns the answer back to the main program. The main program below has two variables num1 and num2. It passes these values into the function and prints the result.
def age(x):
   if x > 18:
      print(“Old enough to watch film”
   else:
      print(“Not old enough to watch film”)

age = input(“Enter your age “)
age(age)
This code uses a function and passes a parameter/value into it, however it does not return anything back to the main program.
variable = “text”
print(variable[x])
This is used to access characters in a string, by replacing the x for the character number you want.
word = “Hello World”
letter = word[0]
print(letter)
The code will access the first character (0) from the word variable and print the letter. In this example it would print “H”
variable.startswith(‘x’)
This checks if the variable starts with a particular character
word = “Hello World”
word.startswith(“W”)
This code would return False as the variable word does not start with a capital W
len(variable)
This is used to find the length of a variable
word = “Hello World”
len(word)
The len() function will return the value 11 as there are 11 characters (including spaces)
variable.count(‘x’)
This is used to count how many times a character appears in a string.
word = “Hello World”
print(word.count(‘o’))
This code would return the value 2, as it counts the number of ‘o’s in the variable word.
variable[start:end]
This is used to get a certain number of characters in a variable
word = “Hello World”
#gets the first three characters i.e. Hel
print(word[0:3])
#gets the last three characters i.e. rld
print(word[-3:])
#gets all but the last three characters #i.e. Hello Wo
print(word[:-3])
variable.upper()
This is used to change the case of a string to upper case
string = “Hello World”
print(string.upper())
This code would display HELLO WORLD on screen
variable.lower()
This is used to change the case of a string to lower case
string = “Hello World”
print(string.lower())
This code would display hello world on screen
variable.isalnum()
This checks if the variable only contains alpha numeric characters
word = “Hello World”
word.isalnum()
This code would return False as the variable word contains a space which is not an alphabetic character
variable.isalpha()
This checks if the variable only contains alphabetic characters
word = “Hello World”
word.isalpha()
This code would return False as the variable word contains a space which is not an alphabetic character
variable.isdigit()
This checks if the variable only contains digits
number = 12345
number.isdigit()
This code would return True as the variable number contains only digits
variable.endswith(‘x’)
This checks if the variable ends with a particular character
word = “Hello World”
word.endswith(“W”)
This code would return False as the variable word does not end with a capital W
fabs(variable)
This finds the absolute value of a variable i.e. removes any negative
from math import *
number = -45.65
answer = fabs(number)
print(answer)
This code would return 45.65 as fabs() removes any negative from a number
ceil(variable)
This finds the next whole number up from the number entered
from math import *
number = 45.23
answer = ceil(number)
print(answer)
This code would return 46 as ceil() always rounds up to the next whole number
floor(variable)
This finds the next whole number down from the number entered
from math import *
number = 45.78
answer = floor(number)
print(answer)
This code would return 45 as floor() always rounds down to the next whole number
sqrt(variable)
This finds square root of a variable
from math import *
number = 16
answer = sqrt(number)
print(answer)
This code would return 4 as sqrt() square roots a number, the square root of 16 is 4.
ceil(variable / 10) * 10
This finds the next higher multiple of 10 from the value in the variable.
from math import *
number = 16
answer = ceil(number / 10) * 10
print(answer)
This code would return 20 as the next multiple of 10 from 16 is 20.