All Variables and Constants  String manipulation  Builtin functions  Input and output  Arrays  Conditional logic  Repetition / Iteration  Functions / Procedures 

Show:

Skill
Description
Pseudocode (Edexcel)
VB.NET
Python
Pseudocode (OCR)
Integer variables
   

Integers are whole numbers

Variables let you store data

Integer variables let you store whole numbers

In this example, a variable called score is declared then set to the integer value of 100

INTEGER score SET score TO 100
Dim score As Integer score = 100
score = 100
score = 100
Real variables
   

Reals are numbers that can contain a decimal place.

Variables let you store data.

A real variable lets you store a number that can contain a decimal place.

In this example, a variable called height is declared then set to the real value of 6.2

REAL height SET height TO 6.2
Dim height As Double height = 6.2
height = 6.2
height = 6.2
Boolean variables
   

Boolean means one of two possible values: usually True or False.

Variables let you store data.

Boolean variables let you store the either value True or False, but nothing else

In this example, a variable called hungry is declared then set to True

BOOLEAN hungry SET hungry TO True
Dim hungry As Boolean hungry = True
hungry = True
hungry = true
Character variables
   

Characters are single letters or digits such as '1', 'H' or '?'

Variables let you store data.

Character variables let you store a single letter, number or punctuation mark.

In this example, a variable called letter is declared then set to a full stop.

CHARACTER letter SET letter TO '.'
Dim letter As Char letter = '.'
letter = '.'
letter = "."
Integer constants
   

Integers are whole numbers (wiith no decimal places).

Constants store a value that is set once and then never changes.

Integer constants let you give a whole number a name so you can use it to make your code easier to read or to set options for your code that the user wont be able to change.

In this example, a constant called NUMBER_OF_TRIES is set to the integer value of 10

CONST INTEGER NUMBER_OF_TRIES SET NUMBER_OF_TRIES TO 10
Const NUMBER_OF_TRIES As Integer = 10
NUMBER_OF_TRIES = 10
NUMBER_OF_TRIES = 10
Real constants
   

Reals are numbers that can contain a decimal place.

Constants store a value that is set once and then never changes.

Real constants let you give a decimal number a name so you can use it to make your code easier to read or to set options for your code that the user wont be able to change.

In this example, a constant called PI is set to the real value of 3.141

 

CONST REAL PI SET PI TO 3.141
Const PI As Double = 3.141
PI = 3.141
PI = 3.141
Boolean constants
   

Boolean means one of two values (usually either True or False).

Constants store a value that is set once and then never changes.

Boolean constants let you give a boolean value a name so you can use it to make your code easier to read or to set options for your code that the user wont be able to change.

In this example, a constant called CHEAT_MODE is set to the boolean value of True

CONST BOOLEAN CHEAT_MODE SET CHEAT_MODE TO True
Const CHEAT_MODE As Boolean = True
CHEAT_MODE = True
CHEAT_MODE = false
Character constants
   

Characters are single letters or digits such as '1', 'H' or '?'

Constants store a value that is set once and then never changes.

Character constants let you give a character value a name so you can use it to make your code easier to read or to set options for your code that the user wont be able to change.

In this example, a constant called KEY_QUIT is set to the character value of 'Q'

CONST CHARACTER KEY_QUIT SET KEY_QUIT TO 'Q'
Const KEY_QUIT As Char KEY_QUIT = 'Q'
KEY_QUIT = 'Q'
KEY_QUIT = "Q"
String variables
    

A string is some text such as "Hello" or "Area 51"

Variables let you store data.

String variables let you store text.

In this example a variable called name is set to the string value of "Bob"

STRING name SET name TO "Bob"
Dim name As String name = "Bob"
name = "Bob"
name = "Bob"
String constants
    

A string is some text such as "Hello" or "Area 51"

Constants store a value that is set once and then never changes.

String constants let you give some text data a name so that you can use it to make your code easier to read or set options for your code that the user wont be able to change.

In this example, a constant called ERROR_MESSAGE is set to the string value of "Don't panic!"

CONST STRING ERROR_MESSAGE SET ERROR_MESSAGE TO "Don't panic!"
Const ERROR_MESSAGE As String = "Don't panic!"
ERROR_MESSAGE = "Don't panic!"
ERRR_MESSAGE = "Don't panic!"
Concatenating strings
   

A string is some text such as "Hello"

Concatenating means joining together or adding / appending on to the end.

Concatenating strings means joining two strings together.

In this example, two strings (first_name and last_name) are concatenated (joined together) and saved in another string variable called full_name with a space in between them.

STRING first_name STRING last_name STRING full_name SET first_name TO "Bob" SET last_name TO "Builder" SET full_name TO first_name & " " & last_name
Dim first_name As String Dim last_name As String Dim full_name As String first_name = "Bob" last_name = "Builder" full_name = first_name & " " & last_name
first_name = "Bob" last_name = "Builder" full_name = Bob + " " + last_name
first_name = "Bob" last_name = "Builder" full_name = Bob + " " + last_name
Length of a string
    

A string is some text such as "Hello"

The length of a string means how many characters (including spaces, numbers and punctuation) there are in that string

This example createa a string called name and sets it to "Bob". It counts how many characters are in that string and stores the answer (3) into a variable called l

STRING name SET name TO "Bob" INT l SET l TO LENGTH(name)
Dim name As String name = "bob" Dim l As Integer l = LEN(name)
name = "Bob" l = len(name)
name = "Bob" l = name.length
Getting a character from a string
   

A string is some text such as "Hello"

A character is a single letter or digit.

Sometimes it's useful to get the 1st, 2nd or whichever character from a string.

This example gets the first character of a string called name and stores it into a variable called first_letter

STRING name SET name TO "Bob" CHAR first_letter SET first_letter TO name[0]
Dim name As String name = "Bob" Dim first_letter As Char first_letter = name(0)
name = "Bob" first_letter = name[0]
name = "Bob" first_letter = name.subString(0,1)
Choose a random number
   

Computers can't think for themselves - they can only follow instructions., so getting them to choose a number that is truely random is not easy. Thankfully, most programming languages have a function that will choose a number for you that appears to be chosen at random.

This example generates a random integer between 0 and 10 and saves it into a variable called r

INTEGER r SET r TO RANDOM(10)
Dim r As Integer r = Rnd() * 10
import random r = random.randint(0, 10)
// not defined in pseudocode spec so this should never come up in an exam // this is just a guess r = random(0, 10)
Comments
  

Comments don't affect how the code runs. They're there to explain the code so that the programmer (or someone else) can understand what the code does. 

Well written comments describe what a line or section of code does. They make your code easier to maintain / extend / improve / debug in the future.

 

# Comments start with a hash
' Comments start with an apostrophe
# Comments start with a hash
// Comments start with two forward slashes
Displaying text
   

Most programs need to output text to the user. 

This example displays the text "Hello" to the screen

SEND "Hello" TO DISPLAY
MsgBox("Hello")
print("Hello")
print("Hello")
Displaying a string variable
   

A string variable lets your program store text that might change as your program runs.

This example creates a string variable called name and displays it to the screen.

STRING name SET name TO "Bob" SEND name TO DISPLAY
Dim name As String name = "Bob" MsgBox(name)
name = "Bob" print(name)
name = "Bob" print(name)
Displaying an integer variable
   

An integer variable lets your program store a whole number that might change as your program runs.

This example creates an integer variable called score and displays it to the screen.

INTEGER score SET score TO 10 SEND score TO DISPLAY
Dim score As Integer score = 10 MsgBox(score)
score = 10 print(str(score))
score = 10 print(str(score))
Displaying a mixture of text and variables
    

Variables let your program store data of a particular data type.

Integer variables store whole numbers. String variables store text.

Sometimes you need to combine text with integer variables and string variables when you display it to the screen.

This example has a string variable called name (set to "Bob") and an integer variable called score (set to 10). It combines both variables with some text to display the message "Bob has 10 points"

INTEGER score SET score TO 10 STRING name SET name TO "Bob" SEND name & " has " & score & " points"
Dim score As Integer score = 10 Dim name As String name = "Bob" MsgBox(name & " has " & score & " points")
score = 10 name = "Bob" print(name + "has " + str(score) + " points")
score = 10 name = "Bob" print(name + "has " + str(score) + " points")
Get user input
   

Most programs need to get the user to type in data that controls how the program behaves.

This program asks the user for their name and saves the result into a string variable called name.

RECEIVE name FROM (STRING) KEYBOARD
Dim name As String name = InputBox()
# python 3 name = input() # python 2 name = raw_input()
name = input()
Ask the user to enter a string
   

A string is some text that can contain more than one letter, number, space or punctuation mark. 

This program asks the user their name and saves the result into a string variable called name.

SEND "What is your name?" TO DISPLAY RECEIVE name FROM (STRING) KEYBOARD
Dim name As String name = InputBox("What is your name?")
# python 3 name = input("What is your name?") # python 2 name = raw_input("What is your name?")
name = input("What is your name?")
Ask the user to enter an integer
   

An integer is a whole number.

This program asks the user to type in their age. Whatever the user types in is then saved into an integer variabled called age.

SEND "How old are you?" TO DISPLAY RECEIVE age FROM (INTEGER) KEYBOARD
Dim age As Integer age = InputBox("How old are you?")
# python 3 name = int(input("How old are you?")) # python 2 name = int(raw_input("How old are you?"))
name = int(input("How old are you?"))
Write a string to a file
   

A string is some text that can contain more than one letter, number, space or punctuation mark.

This example writes the string "Hello world" to the file "output.txt"

WRITE "output.txt" "Hello world"
My.Computer.FileSystem.WriteAllText("output.txt", "Hello world", False) ' Change the False to True if you want to ' append text to the end of the file ' rather than overwrite the file
# open the file f = open("output.txt", "w") # write to the file f.write("Hello world") # close the file so it can be read by other programs f.close()
// open the file f = openWrite("output.txt") // write to the file f.writeLine("Hello world") // close the file so it can be read by other programs f.close()
Write an integer to a file
   

An integer is a whole number (without any decimal places).

This example writes the numbers 1-10 into a file called numbers.txt

FOR num FROM 1 TO 10 DO WRITE "numbers.txt", num END FOR
' Open the file numbers.txt Dim s As System.IO.StreamWriter s = My.Computer.FileSystem.OpenTextFileWriter("numbers.txt", False) ' Loop from 1 to 10 Dim num As Integer For num = 1 To 10 ' Write the number s.WriteLine(num) Next ' Close the file so it can be read by other programs s.Close()
# open the file f = open("numbers.txt", "w") for num in range(1, 10): # write number to the file f.write(num) # add blank line to file f.write("\n") # close the file so it can be read by other programs f.close()
// open the file f = openWrite("numbers.txt") for num = 1 to 10 // write number to the file f.writeLine(num) next num // close the file so it can be read by other programs f.close()
Write data to a csv file
   

A csv file stands for a Comma-separated-values file. It will open as a spreadsheet (often in Excel) with lots of data organised into rows and columns.

When you open the csv file in a text editor (like notepad), the value for each cell is separated by a comma. Each row is written on a new line.

This example writes the 3 times table to a file called "timestables.csv":

e.g:

1, 3

2, 6

3, 9

4, 12

etc...

FOR num FROM 1 TO 10 DO WRITE "timestables.csv", num, num * 3 END FOR
' Open the file numbers.txt Dim s As System.IO.StreamWriter s = My.Computer.FileSystem.OpenTextFileWriter("timestables.csv", False) ' Loop from 1 to 10 Dim num As Integer For num = 1 To 10 ' Write the number, a comma, then the number * 3. All on separate lines s.Write(num) s.Write(",") s.Write(num * 3) s.Write(vbNewLine) Next ' Close the file so it can be read by other programs s.Close()
# open the file f = open("timestables.csv", "w") for num in range(1, 10): # write to the file f.write(num) f.write(",") f.write(num*3) f.write("\n") # close the file so it can be read by other programs f.close()
// open the file f = openWrite("timestables.csv") for num = 1 to 10 // write to the file f.writeLine(num + "," + num*3) next num // close the file so it can be read by other programs f.close()
Create array of strings
   

An array let your store more than one piece of data into the same variable as an ordered list.

This example stores three strings into the array called names.

SET names TO ["Percy", "James", "Gordon"]
Dim names As String() names = {"Percy", "James", "Gordon"}
names = ["Percy", "James", "Gordon"]
array names[3] names[0] = "Percy" names[1] = "James" names[2] = "Gordon"
Create array of numbers
   

An array lets you store more than one piece of data into the same variable as an ordered list.

This example stores three numbers into the array called ages.

SET ages to [14, 15, 14]
Dim ages As Integer() ages = {14, 15, 14}
ages = [14, 15, 14]
array ages ages[0] = 14 ages[1] = 15 ages[2] = 14
Access data in an array
   

An array lets you store more than one piece of data into the same variable as an ordered list.

Data in an array can be accessed using an index. This is a number which defines the position in the list, which starts counting from 0

This example displays the first string in an array called names

SET names TO ["Percy", "James", "Gordon"] SEND names[0] TO DISPLAY
Dim names As String() names = {"Percy", "James", "Gordon"} MsgBox(names(0))
names = ["Percy", "James", "Gordon"] print(names[0])
array names[3] names[0] = "Percy" names[1] = "James" names[2] = "Gordon" print(names[0])
Create a 2D array
   

If an array is like a list of data, a 2d array is like a grid of data where the data is stored in one variable but organised into rows and columns like a spreadsheet.

This example stores details of 3 different fruit for a supermarket.

It will then display the colour of the first fruit.

The first index will select the row then the second index selects the column

SET fruit TO [["Plum", "Purple"], ["Apple", "Red"], ["Banana", "Yellow"]] SEND fruit[0,1] TO DISPLAY
Dim fruit As String(,) fruit = {{"Plum", "Purple"}, {"Apple", "Red"}, {"Banana", "Yellow"}} MsgBox(fruit(0,1))
fruit = [["Plumb", "Purple"], ["Apple", "Red"], ["Banana", "Yellow"]] print(fruit[0][1])
array fruit[3][2] fruit[0][0] = "Plumb" fruit[0][1] = "Purple" fruit[1][0] = "Apple" fruit[1][1] = "Red" fruit[2][0] = "Banana" fruit[2][1] = "Yellow" print(fruit[0][1])
IF statement
   

If you want your code to make a decision you'll need an IF statement.

This example asks the user how old they are and checks that they've entered a number bigger than 0

RECEIVE age FROM (INTEGER) KEYBOARD IF age < 0 THEN SEND "You can't be less than 0 years old!" ENDIF
Dim age As String age = InputBox("How old are you?") If age < 0 Then MsgBox("You can't be less than 0 years old!") End If
age = input("How old are you?") if age < 0: print("You can't be less than 0 years old!")
age = input("How old are you?") if age < 0 then print("You can't be less than 0 years old!") endif
IF ... ELSE statement
   

If you want your code to choose between two possibilities you'll need an IF ... ELSE statement.

This example asks the user what their name is. If they answer the question it says hello. If they don't answer the question it displays an error message.

SEND "What's your name?" TO DISPLAY RECEIVE name FROM (STRING) KEYBOARD IF name = "" THEN SEND "You have to enter your name" TO DISPLAY ELSE SEND "HELLO " & name TO DISPLAY END IF
Dim name As String name = InputBox("What is your name?") If name = "" Then MsgBox("You have to enter your name") Else MsgBox("Hello " & name) End If
name = input("What is your name?") if name == "": print("You have to enter your name") else: print("Hello " + name)
name = input("What is your name?") if name == "" then print("You have to enter your name") else print("Hello " + name) endif
Not equal to
   

You can test if two expressions are the same using the equal to or not equal to operator.

An expression can be a variable or combination of variables & data (e.g. 1 + 1)

An operator is a symbol that means add, subtract or something similar.

This example asks the user to enter a temperature  of a bath (in degrees Celsius) and then follows the following rules:

Equal to 37 degrees: says "Perfect - that's body temperature"

Not equal to 37 degrees: "Not body temperature"

SEND "What's the temperature of the bath?" TO DISPLAY RECEIVE temperature FROM (INTEGER) KEYBOARD IF temperature = 37 THEN SEND "Perfect - that's body temperature" TO DISPLAY END IF IF temperature <> 37 THEN SEND "Not body temperature" TO DISPLAY END IF
Dim temperature As Integer temperature = InputBox("What's the temperature of the bath?") If temperature = 37 Then MsgBox("Perfect - that's body temperatuyre") End If If temperature <> 37 Then MsgBox("Not body temperature") End If
temperature = int(input("What's the temperature of the bath?") if temperature == 37: print("Perfect - that's body temperature") if temperature != 37: print("Not body temperature")
temperature = int(input("What's the temperature of the bath?") if temperature == 37 then print("Perfect - that's body temperature") endif if temperature != 37 then print("Not body temperature") endif
Greater than or less than
   

If you need to compare two expressions you will need the greater than or less than operators.

An expression can be a variable or combination of variables & data (e.g. 1 + 1)

An operator is a symbol that means add, subtract or something similar.

This example asks the user to enter a password and displays how strong that password is based purely on the length:

Less than 5 characters: weak

More than or equal to 8 characters: strong

Otherwise: medium

SEND "Please enter a password" TO DISPLAY RECEIVE password FROM (STRING) KEYBOARD IF LENGTH(password) >= 8 THEN SEND "strong" TO DISPLAY ELSE IF LENGTH(password) < 5 THEN SEND "weak" TO DISPLAY ELSE SEND "medium" TO DISPLAY END IF END IF
Dim password As String password = InputBox("Please enter a password") If Len(password) >= 8 Then MsgBox("strong") Else If Len(password) < 5 Then MsgBox("weak") Else MsgBox("medium") End If End If
password = input("Please enter a password") if len(password) >= 8: print("strong) else: if len(password) < 5: print("weak") else: print("medium")
password = input("Please enter a password") if password.length >= 8 then print("strong) else if password.length < 5 then print("weak") else print("medium") endif endif
While loop
   

A while loop will keep repeating whilst a condition is met (it will stop repeating when the condition is no longer met). 

This is known as a pre-conditioned loop because the program checks if the condition has been met before the code in the loop runs. This means that the minimum number of times the loop will run could be 0.

It is also an example of indefinite iteration because the loop could carry on forever unless the condition is met.

This example program keeps asking the user "Are we nearly there yet" until they say "yes"

STRING nearly_there SET nearly_there TO "no" WHILE nearly_there <> "yes" SEND "Are we nearly there yet?" TO DISPLAY RECEIVE nearly_there FROM (STRING) KEYBOARD END WHILE
Dim nearly_there As String nearly_there = "no" While nearly_there <> "yes" nearly_there = InputBox("Are we nearly there yet?") End While
nearly_there = "no" while nearly_there != "yes": nearly_there = input("Are we nearly there yet?")
nearly_there = "no" while nearly_there != "yes" nearly_there = input("Are we nearly there yet?") endwhile
Repeat Until loop
   

A repeat until loop will keep repeating until a condition is met.

This is known as a post-conditioned loop because the program checks if the condition has been met after the code in the loop runs. This means that the loop will always run at least once.

It is also an example of indefinite iteration because the loop could carry on forever if the condition is never met.

This example program keeps asking the user "Are we nearly there yet?" until they say "yes"

REPEAT SEND "Are we nearly there yet?" TO DISPLAY RECEIVE nearly_there FROM (STRING) KEYBOARD UNTIL nearly_there = "yes"
Do nearly_there = InputBox("Are we nearly there yet?") Loop Until nearly_there = "yes"
# there is no post-conditioned loop in python # but this works in the same way while True: nearly_there = input("Are we nearly there yet?") if nearly_there == "yes": break
do nearly_there = input("Are we nearly there yet?") until nearly_there == "yes"
Repeat ... times
   

Repeating ... number of times is known as a count controlled loop because you specify exactly how many times the loop will repeat.

This example program will repeat the word "Why?" 10 times

REPEAT 10 TIMES SEND "Why?" TO DISPLAY END REPEAT
For i = 1 to 10 MsgBox("Why?") Next i
for i in range(10): print("Why?")
for i = 0 to 9 print("Why?") next i
For loop
   

A for loop is a count-controlled loop which means it your code says exactly how many times the loop should repeat. 

A for loop will use a variable to count between the minimum and maximum value. This variable is called the index, which is why for loops often use the variable i.

This example will count from 10 to 20

FOR i FROM 10 TO 20 DO SEND i TO DISPLAY END FOR
For i = 10 To 20 MsgBox(i) Next i
for i in range(10,21): print(i)
for i = 10 to 20 print(i) next i
For loop (with step)
   

for loop is a count-controlled loop which means it your code says exactly how many times the loop should repeat. 

A for loop will use a variable to count between the minimum and maximum value. This variable is called the index, which is why for loops often use the variable i.

Rather than increasing the index by 1 each time, you can step up by any amount until you reach the maximum.

This example will count down from 10 to 1 then say "Blast off!" 

FOR i FROM 10 TO 1 STEP -1 DO SEND i TO DISPLAY END FOR SEND "Blast off!"
For i = 10 To 1 Step -1 MsgBox(i) Next i MsgBox("Blast off!")
for i in range(10,0,-1): print(i) print("Blast off!")
// There isn't a for loop with step specified // but the following while loop does the same thing i = 10 while i >= 0 print(i) i = i - 1 endwhile print("Blast off!")
For Each loop
   

A for each loop means the code in the loop will run once for each item in an array.

This means it is a count-controlled loop because the number of times the loop will run is not dependent on a condition being met: you know how many times it will repeat in advance.

This example will display the lyrics for "The wheels on the ... go round and round"  for an array containing the strings "bus", "car" and "tram"

SET vehicles TO ["bus", "car", "tram"] FOR EACH vehicle FROM vehicles DO SEND "The wheels on the " & vehicle & " go round and round" TO DISPLAY SEND "Round and round, round and round" TO DISPLAY SEND "The wheels on the " & vehicle & " go round and round" TO DISPLAY SEND "All day long" END FOREACH
dim vehicles As String() vehicles = {"bus", "car", "tram"} For Each vehicle As String In vehicles Msgbox("The wheels on the " & vehicle & " go round and round") MsgBox("Round and round, round and round") MsgBox("The wheels on the " & vehicle & " go round and round") Msgbox("All day long") Next For
vehicles = ["bus", "car", "tram"] for vehicle in vehicles: print("The wheels on the " + vehicle + " go round and round") print("Round and round, round and round") print("The wheels on the " + vehicle + " go round and round") print("All day long")
// there's no for each loop specified // but the following code does the same thing array vehicles vehicles[0] = "bus" vehicles[1] = "car" vehicles[2] = "tram" for i = 0 to 2 vehicle = vehicles[i] print("The wheels on the " + vehicle + " go round and round") print("Round and round, round and round") print("The wheels on the " + vehicle + " go round and round") print("All day long") next i
Create and use a procedure
   

A procedure is a section of code that has a name that you can re-use to do something useful.

A procedure definition is the code that tells the computer what to do whenever that procedure runs.

The procedure wont actually do anything until you call it.

This example defines a procedure that shows a random word then calls it twice.

# define ShowRandomWord procedure PROCEDURE ShowRandomWord() BEGIN PROCEDURE SET words TO ["wibble", "wobble", "plop"] INTEGER i SET i TO RANDOM(2) SEND words[i] T DISPLAY END PROCEDURE # Call ShowRandomWord twice ShowRandomWord() ShowRandomWord()
' define ShowRandomWord procedure Sub ShowRandomWord() dim words As String() words = {"wibble", "wobble", "plop"} dim i as Integer i = Rnd() * 2 Msgbox(words(i)) End Sub ' Call ShowRandomWord twice ShowRandomWord() ShowRandomWord()
import random # define show_random_word procedure def show_random_word(): words = ["wibble", "wobble", "plop"] print(random.choice(words)) # call show_random_words twice show_random_word() show_random_word()
// this code assumes there is a function defined called random(min, max) // which chooses a random number between a minimum and maximum (inclusive) // this is not in the pseudocode spec // define show_random_word procedure procedure show_random_word() switch random(1, 3) case 1: print("wibble") case 2: print("wobble") case 3: print("plop") endswitch endprocedure // call show_random_words twice show_random_word() show_random_word()
Create and use a procedure with parameters
   

A procedure is a section of code that has a name, that you can re-use to do something useful.

Parameters are variables that allow you to send data to the procedure to customise what it does or how it works. 

A procedure definition is the code that tells the computer what to do whenever that procedure runs. The parameters are the variables named in brackets after the procedure name.

The procedure wont actually do anything until you call it.

This example defines a procedure which will display a random number. It has two parameters which allow you to set the minimum and maximum number the random number will be between.  

This procedure is called to show a random number between 10 and 20 and then called again to choose a random number between 50 and 100.

# Define the procedure PROCEDURE ShowRandomBetween(min, max) BEGIN PROCEDURE INTEGER n SET n TO RANDOM(max - min) + min SEND n TO DISPLAY END PROCEDURE # Call the procedure ShowRandomBetween(10, 20) ShowRandomBetween(50, 100)
' Define the procedure Sub ShowRandomBetween(min As Integer, max As Integer) dim n As Integer n = (Rnd() * (max - min)) + min MsgBox(n) End Sub ' Call the procedure ShowRandomBetween(10, 20) ShowRandomBetween(50, 100)
import random # define the procedure def show_random_between(min, max): print(random.randint(min, max)) # call the procedure show_random_between(10, 20) show_random_between(50, 100)
// this code assumes there is a function defined called random(min, max) // which chooses a random number between a minimum and maximum (inclusive) // this is not in the pseudocode spec // define the procedure prcedure show_random_between(min, max): print(random(min, max)) endprocedure // call the procedure show_random_between(10, 20) show_random_between(50, 100)
Create and use a function
   

A function is like a procedure except that it always returns a value.

This return value is calculated when the function is called and can be saved into a variable or used later in the program.

Both functions and procedures are sections of code that have been given a name, which can be re-used to do something useful.

This example defines a function which chooses a random word. This function is called twice with the return value being stored into separate variables.

# define ChooseRandomWord function FUNCTION ChooseRandomWord() BEGIN FUNCTION SET words TO ["wibble", "wobble", "plop"] INTEGER i SET i TO RANDOM(2) RETURN i END FUNCTION # Call ChooseRandomWord twice STRING FirstWord SET FirstWord TO ChooseRandomWord() STRING SecondWord SET SecondWord TO ChooseRandomWord()
' define ShowRandomWord function Function ShowRandomWord() dim words As String() words = {"wibble", "wobble", "plop"} dim i As Integer i = Rnd() * 2 Return words(i) End Function ' Call ShowRandomWord twice Dim FirstWord As String FirstWord = ShowRandomWord() Dim SecondWord As String SecondWord = ShowRandomWord()
import random # define choose_random_word function def choose_random_word(): words = ["wibble", "wobble", "plop"] return random.choice(words) # call choose_random_words twice first_word = choose_random_word() second_word = choose_random_word()
// this code assumes there is a function defined called random(min, max) // which chooses a random number between a minimum and maximum (inclusive) // this is not in the pseudocode spec // define choose_random_word function function choose_random_word() switch random(1, 3) case 1: return "wibble" case 2: return "wobble" case 3: return "plop" endswitch endfunction // call choose_random_words twice first_word = choose_random_word() second_word = choose_random_word()
Create and use a function with parameters
   

A function is like a procedure except that it always returns a value.

Parameters are variables that allow you to send data to the function to customise what it does or how it works. 

The parameters are the variables named in brackets after the function name.

This return value is calculated when the function is called and can be saved into a variable or used later in the program.

Both functions and procedures are sections of code that have been given a name, which can be re-used to do something useful.

This example defines a function which will generate and return a random number. It has two parameters which allow you to set the minimum and maximum number the random number will be between.  

This function is called to choose a random number between 10 and 20 and then called again to choose a random number between 50 and 100. Both numbers are returned and saved into separate variables.

# Define the function FUNCTION ChooseRandomBetween(min, max) BEGIN FUNCTION INTEGER n SET n TO RANDOM(max - min) + min RETURN n END FUNCTION # Call the function INTEGER FirstNumber SET FirstNumber = ChooseRandomBetween(10, 20) INTEGER SecondNumber SET SecondNumber TO ChooseRandomBetween(50, 100)
' Define the function Sub ShowRandomBetween(min As Integer, max As Integer) dim n As Integer n = (Rnd() * (max - min)) + min Return n End Function ' Call the function Dim FirstNumber As Integer FirstNumber = ShowRandomBetween(10, 20) Dim SecondNumber As Integer SecondNumber = ShowRandomBetween(50, 100)
import random # define the function def choose_random_between(min, max): print(random.randint(min, max)) # call the function first_number = choose_random_between(10, 20) second_number = choose_random_between(50, 100)
// this code assumes there is a function defined called random(min, max) // which chooses a random number between a minimum and maximum (inclusive) // this is not in the pseudocode spec // define the function function choose_random_between(min, max): return random(min, max) endfunction // call the function first_number = choose_random_between(10, 20) second_number = choose_random_between(50, 100)