Playground

Output Great job!

        

Correct - great job!

Your code runs, but it does not produce the correct output

Your code was given the test input(s): True, 1.2324

The correct output is:

A syntax error means that the code isn't able to run. Check that:

  • All opening brackets and quotation marks are closed
  • All variables are typo-free (capitalisation matters!)
  • You are asking for inputs using a sensible datatype
  • You are asking for inputs in the order they appear in the question
  • Indentation is consistent
Show cheatsheet

String output

Use the print function to output a string. Don't forget quotation marks!

print("Hello world")

Variable initialisation

Use the general format identifier = value to assign a value to a variable

myFavouriteWord = "splodge"
weeklyIncome = 54.3

Variable names can only include letters, numbers and an underscore _. Additionally, variables cannot start with a number.

Variable output

Use the print function to output the contents of a variable. Make sure not to use quotation marks, which will instead output the string of the variable's name.

print(weeklyIncome)

String concatenation

Use the + operator to concatenate (join) strings together. You cannot concatenate different datatypes, so will have to cast all floats and integers to a string using the str function.

print("Hello " + "world")
print("Hello " + userName)
print(str(quantity) + " bananas")

Note: You can also multiply strings to repeat them. For instance, "Hello"*4

User input

Use the general form identifier = dataType(input("prompt")) to ask a user for an input.

dataType can be any of the casting functions - str, int, float or bool.

name = str(input("Enter your name: "))
age = int(input("Enter your age: "))
height = float(input("Enter your height: "))

If statements

An if statement will run a block of indented code if a boolean condition is true. It has the following general format

if condition:
  do something

For instance, to output the string "hello" if the contents of the variable 'number' is greater than 10, the following if statement can be used

if number > 10:
  print("hello")

If/else statements

An if/else statement will run one block of indented code if a boolean condition is true, and another if the condition is false. It has the following general format

if condition:
  do something
else:
  do something else

For instance, to output the string "hello" if the contents of the variable 'number' is greater than 10, and "goodbye" otherwise, the following if/else statement can be used

if number > 10:
  print("hello")
else:
  print("goodbye")

If/elif/else statements

An if/elif/else statement allows if statements to be chained together. Only one of its indented blocks will be run. It has the following general format

if condition:
  do something
elif another condition:
  do another thing
else:
  do something else

For instance, to output the string "Premium" if the contents of the variable 'price' is greater than 10, "Standard" if it greater than 5 and "Economy" otherwise, the following if/else statement can be used

if price > 10:
  print("Premium")
elif price > 5:
  print("Standard")
else:
  print("Economy")

Nested if statements

If statements can be used to perform more complicated selection by using indentation to include one if statement in another. The general format is:

if condition:
  if another condition:
    do something
  else:
    do something else
else:
  do another thing

Note that solo-if, if/else and if/elif/else blocks can all be nested.

Count-controlled iteration

To repeat a block of code a set number of times, count-controlled iteration can be used. The general format is:

for variable in range(start, end):
  do something

Note that the start number is inclusive and the end number is exclusive

For instance, to output the numbers 5 to 10, the following code can be used

for number in range(5, 11):
  print(number)

An additional step argument can be given to the range function that determines what number to go up (or down) in. The default is 1.

for number in range(10, 0, -2):
  print(number)

Condition-controlled iteration

To repeat a block of code until a condition is false, condition-controlled iteration can be used. The general format is:

while condition:
  do something

You'll usually need to create a variable with a starting condition for the while loop. For instance, to output the numbers 5 to 8 the following code can be used:

number = 5
while number <= 8:
  print(number)
  number = number + 1

Be careful when constructing the while loop's condition - it's easy to create an infinite loop!

Initialising a 1D array

The general format to initialise a one-dimensional array is:

identifier = [elementOne, elementTwo, elementThree]

To store the numbers 1-5 in a variable numbers, the following code can be used:

numbers = [1, 2, 3, 4, 5]

To initialise an empty array, use:

identifier = []

Accessing a 1D array

The general format to access an element in a one-dimensional array is:

identifier[index]

To output the 3rd element from the array names, the following code can be used:

print(names[2])

Remember, indexes start at 0.

Modifying a 1D array

The general format to modify an element in a one-dimensional array is:

identifier[index] = value

To change the 3rd element from the array names to "Felix", the following code can be used:

names[2] = "Felix"

Remember, indexes start at 0.

Appending to a 1D array

The general format to append an element in a one-dimensional array is:

identifier.append(value)

To append the string "Felix" to the array names to , the following code can be used:

names.append("Felix")

Iterating over a 1D array

The general format to iterate over a one-dimensional array is:

for element in array:
  do something with element

To output all the elements in the array names, the following code can be used:

for name in names:
  print(name)

Initialising a 2D array

The general format to initialise a two-dimensional array is:

identifier = [[a, b, c], [x, y, z]]

You may find it more readable to lay out your code in rows and columns, for instance:

identifier = [
  [a, b, c],
  [x, y, z]
]

Accessing a 2D array

The general format to access an element in a two-dimensional array is:

identifier[rowIndex][columnIndex]

To output the 3rd element from the second row of the array marks, the following code can be used:

print(marks[1][2])

Remember, indexes start at 0.

Modifying a 2D array

The general format to modify an element in a two-dimensional array is:

identifier[rowIndex][columnIndex] = value

To change the 3rd element in the second row of the array names to "Felix", the following code can be used:

names[1][2] = "Felix"

Remember, indexes start at 0.

Appending to a 2D array

There are two ways of appending to a 2D array - either appending to a row, or appending a whole row.

To append an element to a row, use the following general format:

array[rowIndex].append(value)

To append a whole row, use the following general format:

array.append(["a", "b", "c"])

Iterating over a 2D array

The general format to iterate over a two-dimensional array is:

for row in array:
  for element in row:
    do something with element

Opening and closing a file

To open and close a file the following general format can be used:

file = open("filename.txt", "mode")
do something with file
file.close()

The mode a file is open in can be w for writing, r for reading or a for appending.

Writing to a file

To write to a file, the following general form can be used:

file.write(value + "\n")

By concatenating a newline character (\n) the next line written to the file will start on a new line, instead of continuing on the same line

For example, to write two lines to a file, the following code can be used

file.write("This week's income is:" + "\n")
file.write(weeklyIncome + "\n")

Reading a line from a file

The general form for reading a single line from a file is:

file.readline()

Every time the readline function is called, the next line in the file is read. For example, to output the first two lines in a file the following code can be used:

print(file.readline())
print(file.readline())

Iterating over a file

The general format to iterate over the lines in a file is:

for line in file:
  do something with line

To output every line in a file, the following code can be used:

for line in file:
  print(line)

Note that each line will have a newline character at the end of it. To remove this newline character, use line = line.strip()

Writing comma-seperated values to a file

There are two general ways to write comma-seperated values to a file.

If the values are seperate variables, then use:

file.write(valueOne + "," + valueTwo + "\n")

If the values are in an array, then use:

file.write(",".join(array) + "\n")

Defining a subroutine

There are two types of subroutine - a function, which returns a value, and a procedure, which does not return a value.

The general format to define a function is:

def functionName(parameterOne, parameterTwo):
  do something
  return value

Defining a procedure is similiar, but the return statement is left out:

def procedureName(parameterOne, parameterTwo):
  do something

Calling a subroutine

The general format to call a subroutine is

subroutineName(argumentOne, argumentTwo)

If the subroutine is a function, then something has to be done with the returned value - either output it directly or store it in a variable.

print(functionName(argument))
result = functionName(argument)

Basic arithmetic operations

Python can be used to carry out arithmetic operations on integers and floats (and variables that hold integers and floats).

The result of an operation can be stored in a variable or outputted directly.

print(5 * 10)
age = 45 / 4
weight = weight + 1
print(45 - timeTaken)

String manipulation

Strings (and arrays) can be 'sliced' to obtain a subsection of the original. There are several ways of obtaining different slices:

string[start:stop]

This will return a section starting at the start index and continuing until the character before the stop index.

string[start:]

This will return a section starting at the start index and continuing until the end of the string.

string[:stop]

This will return a section starting at the start of the string and continuing until the character before the stop index.

For example:

string = "abcdefgh"
print(string[3:5]) # "de"
print(string[4:)   # "efgh"
print(string[:3)   # "abc"

Advanced arithmetic operations

Python can be used to perform more complex arithmetic operations.

To raise a number to a power use number ** power. For instance, to find 5 squared, use 5 ** 2

To square root a number, use number ** (1/2)

To find the modulus (remainder of division), use number % divisor. This can be used to check if a number is odd or even - if the modulus when divided by 2 is 0, then the number is even.

To find the quotient (integer value of division), use number // divisor

Finding the length of an array

The len() function is used to find the length of an array.

print(len(names))
arrayLength = len(numbers)

Logical operators

Logical operators can be used to create complex conditions. The three logical operators available are and, or, and not.

if age > 10 and height == 40:
  do something

if age > 10 or height == 40:
  do something

if not(age > 10 and height == 40):
  do something

Initialising a dictionary

The general format to initialise a dictionary is:

identifier = {keyOne: value, keyTwo: value}

To initialise an empty dictionary, use:

identifier = {}

Accessing a dictionary

To access a value in a dictionary, use:

identifier[key]

For example, to output the element stored under the key "blue" in the dictionary colours, use:

colours["blue"]

Modifying a dictionary

The general format to modify an element in a dictionary is:

identifier[key] = value

To change the element stored under the key "blue" in the dictionary colours to 12, the following code can be used:

colours["blue"] = 12

Checking a key is present in a dictionary

To check a key is present in a dictionary, use:

if key in dictionary:
  do something
else:
  do something else

Removing a value from a dictionary

To delete a key (and associated value) from a dictionary, use the following syntax:

del identifier[index]

Iterating over a dictionary

There are several ways to iterate over a dictionary - iterating over the keys, iterating over the values, or iterating over both the keys and the values at the same time.

To iterate over the keys, use:

for key in dictionary.keys():
  do something with 'key'

To iterate over the values, use:

for value in dictionary.values():
  do something with 'value'

To iterate over the both at the same time, use:

for key, value in dictionary.items():
  do something with 'key'
  do something with 'item'

Adding to a dictionary

To add a value to a dictionary under a new key, use:

dictionary[key] = value

Defining a class

To define a class, use the keyword class followed by the class name:

class YourClassName:
  class body

For example, to define a class named 'Alien':

class Alien:
  Attributes and methods of Alien

To initialise a class, use the __init__ method:

class ClassName:
  def __init__(self, parameter1, parameter2):
    do something

For example, initialising an 'Alien' class with 'name' and 'planet':

class Alien:
  def __init__(self, name, planet):
    self.name = name
    self.planet = planet

Defining properties in a class

Properties are defined in the __init__ method of a class:

class ClassName:
  def __init__(self):
    self.property1 = value1
    self.property2 = value2

For example, defining properties in the 'Alien' class:

class Alien:
  def __init__(self):
    self.name = "Zorg"
    self.planet = "Neptune"

Creating methods in a class

To create a method in a class, define a function inside the class:

class ClassName:
  def methodName(self, parameter1, parameter2):
    do something

For example, creating a method in the 'Alien' class:

class Alien:
  def greet(self):
    print("Hello, I am " + self.name)

Using 'self' in a class

The self keyword is used to access properties and methods within class methods:

class ClassName:
  def yourMethodName(self):
    self.property1
    self.method2()

For example, using 'self' in the 'Alien' class:

class Alien:
  def __init__(self, name):
    self.name = name

  def greet(self):
    print("Hello, I am " + self.name)

Creating an instance of a class

To create an instance of a class, call the class with required parameters:

instanceName = ClassName(parameter1, parameter2)

For example, creating an instance of the 'Alien' class:

alienZorg = Alien("Zorg", "Neptune")

Calling a class's methods

To call a method of a class instance, use the dot notation:

instanceName.methodName(parameters)

For example, calling a method of an 'Alien' instance:

alien1.greet()

Accessing and modifying a class's properties

To access or modify a method of a class instance, use the dot notation:

print(instanceName.property)
instanceName.property = value

For example, to output an Alien's name:

print(alien1.name)

Defining private methods

To make a method private, use the double underscore notation. This prevents the method from being called outside of the class.

class MyClass:
  def __privateMethod(self):
    print("Hello!")

# This will throw an error
myClass = MyClass()
myClass.__privateMethod()

Defining private properties

To make a method private, use the double underscore notation. This prevents the method from being called outside of the class.

class MyClass:
  __privateProperty = "Hello!"

# This will throw an error
myClass = MyClass()
print(myClass.__privateProperty)

Defining accessors and mutators

To define accessors and mutators (also known as getters and setters), create methods that return or modify variables.

class MyClass:
  name = "Manuel"

  def getName(self):
    return self.name

  def setName(self, newName):
    self.name = newName

Inheriting from a class

To inherit from a parent class, put the name of the parent class in brackets when defining it:

class Parent:
  # do something
class Child(Parent):
  # do something else

Using super() to initialise a parent class

Usually, the parent class is initialised automatically. However, if you wish to modify a child's init method, you must use the super() method to initialise the parent

class Parent:
  def __init__(self, name):
    self.name = name
class Child(Parent):
  def __init__(self, name, age):
    super().__init__(name)
    self.age = age

Overriding methods

To override a parent's method, simply just redefine it in the child class

class Parent:
  def output(self):
    print("Hello world!")

class Child(Parent):
  def output(self):
    print("Overriden!")

Using super() to extend a parent's method

To extend a parent's method, as opposed to overriding it, use the super() method to call the parent method.

class Parent:
  def output(self):
    print("Hello world")

class Child(Parent):
  def output(self):
    super().output()
    print("This will also be outputted")

Recursion

A recursive function is a function that calls itself. It is important to include a stop condition to avoid creating an infinite loop.

def recursion(number):
  if number == 1:
    return number
  return recursion(number + 1)

Exception handling

Sometimes a user will enter data that causes an error - for instance, they may enter a string when asked for an integer. To account for this, exception handling is used.

A try-except block is used to catch errors - the except block is run as soon as an error of the given type occurs.

try:
  number = int(input("Enter a number"))
  print(number / 2)
except ValueError:
  print("You did not enter a number")

There are dozens of errors you can account for, but here are a few:

ValueError - when trying to cast to an inappropriate datatype

IndexError - when trying to access an element of an array that does not exist

AttributeError - when trying to access an attribute (or method) that does not exist for the given object

ZeroDivisionError - when trying to divide by zero

KeyError - when trying to access a non-existant key of a dictionary