Python → IB Pseudocode
IB Computer Science
Key rules
- 01Variable names are written in CAPITALS (SCORE, TOTAL); subprogram names keep their case.
- 02Assignment uses
=, and printing usesoutput; reading a value usesinput NAME. - 03Counting loops are
loop I from A to B, where both ends are included, so range(n) becomes 0 to N - 1. - 04Selection is
if … then … else if … else … end if. - 05Arrays are 0-based like Python and Java, and their size is
ARRAY.length.
Contents10 sections
Quick reference
| Concept | Python | IB |
|---|---|---|
| Assignment | x = 5 | X = 5 |
| Output | print("Hi") | output "Hi" |
| Input | name = input() | input NAME |
| If | if x > 3: print(x) | if X > 3 then output Xend if |
| Else if | if x > 3: print(1)elif x > 1: print(2) | if X > 3 then output 1else if X > 1 then output 2end if |
| While loop | while x < 3: x = x + 1 | loop while X < 3 X = X + 1end loop |
| Counting loop | for i in range(5): print(i) | loop I from 0 to 4 output Iend loop |
| Repeat n times | for i in range(3): print("Hi") | loop I from 0 to 2 output "Hi"end loop |
| For each | for x in xs: print(x) | loop I from 0 to XS.length - 1 X = XS[I] output Xend loop |
| Create array | xs = [4, 7, 9] | XS = [4, 7, 9] |
| Array access | print(xs[0]) | output XS[0] |
| Length | print(len(xs)) | output XS.length |
| Function + return | def twice(n): return n * 2print(twice(4)) | function twice(N) returns value return N * 2end functionoutput twice(4) |
| Procedure + call | def show(n): print(n)show(3) | procedure show(N) output Nend procedureshow(3) |
| Integer division | b = a // 2 | B = A div 2 |
| Remainder | b = a % 2 | B = A mod 2 |
| Not equal | print(a != 2) | output A ≠ 2 |
| And / or / not | print(a and not b or b) | output A AND NOT B OR B |
| String join | t = s + "cd" | T = S + "cd" |
| Random 1–6 | r = random.randint(1, 6) | R = RANDOM.randint(1, 6) |
01Basics
IB pseudocode looks a lot like Python. The biggest visible change is that variable names are written in CAPITALS, and printing becomes output. Values do not need a declared type.
Examples8
1.1
Comment
Comments start with // in every standard. Write them before the line they explain.
# Calculate the area of a rectanglearea = 4 * 3// Calculate the area of a rectangleAREA = 4 * 31.2
Assign a variable
IB uses = for assignment and CAPITAL names. Updating a variable is written in full (SCORE = SCORE + 10).
score = 0score = score + 10SCORE = 0SCORE = SCORE + 101.3
Variables of different types
Types are not written in IB pseudocode. Booleans are lower-case true / false.
count = 5price = 2.75name = "Ana"found = FalseCOUNT = 5PRICE = 2.75NAME = "Ana"FOUND = false1.4
Constant
There is no constant keyword, so a constant is just a variable written in capitals that you never change.
MAX_SIZE = 50print(MAX_SIZE)MAX_SIZE = 50output MAX_SIZEtotal = 42print(total)TOTAL = 42output TOTAL1.6
Output text and a value
Several values can be listed after output, separated by commas.
age = 16print("Age:", age)AGE = 16output "Age:", AGEname = input("Enter your name: ")print("Hello " + name)output "Enter your name: "input NAMEoutput "Hello " + NAME1.8
Input a number
Converting the input with int() (or sc.nextInt()) is not written in pseudocode; input simply reads a value.
age = int(input("Enter your age: "))print(age + 1)output "Enter your age: "input AGEoutput AGE + 1Exercises1
Q1.Ask for the user's name and favourite number, then print a message with both.
name = input("Name: ")number = int(input("Favourite number: "))print(name, number)Show answerHide answer
output "Name: "input NAMEoutput "Favourite number: "input NUMBERoutput NAME, NUMBER02Operators
IB uses div and mod for integer division and remainder, ≠ for not-equal and the capitalised words AND, OR, NOT. There is no power operator.
Examples7
2.1
Arithmetic
+ - * / are the same in every standard. / always gives a real (decimal) result.
a = 7b = 2print(a + b)print(a - b)print(a * b)print(a / b)A = 7B = 2output A + Boutput A - Boutput A * Boutput A / Bminutes = 135hours = minutes // 60print(hours)MINUTES = 135HOURS = MINUTES div 60output HOURS2.3
Remainder (modulo)
% becomes mod. Testing mod 2 = 0 is the usual way to check for an even number.
n = 17if n % 2 == 0: print("even")else: print("odd")N = 17if N mod 2 = 0 then output "even"else output "odd"end if2.4
Power
This standard has no power operator, so the expression is copied and flagged. Multiply instead (side * side).
side = 5area = side ** 2print(area)SIDE = 5AREA = side ** 2output AREA- Not directly available in IB: The ** operator has no IB pseudocode equivalent. It was copied unchanged.
x = 4y = 9print(x == y)print(x != y)print(x <= y)print(x >= y)X = 4Y = 9output X = Youtput X ≠ Youtput X <= Youtput X >= Y2.6
Logical and / or / not
Java &&, ||, ! and Python and, or, not all become the capitalised words AND, OR, NOT.
age = 15member = Trueif age >= 12 and age <= 18: print("teen")if age < 5 or age > 65: print("free entry")if not member: print("please register")AGE = 15MEMBER = trueif AGE >= 12 AND AGE <= 18 then output "teen"end ifif AGE < 5 OR AGE > 65 then output "free entry"end ifif NOT MEMBER then output "please register"end iffirst = "Ada"last = "Lovelace"full = first + " " + lastprint(full)FIRST = "Ada"LAST = "Lovelace"FULL = FIRST + " " + LASToutput FULLExercises1
Q1.Convert a number of seconds into minutes and remaining seconds.
seconds = 200minutes = seconds // 60rest = seconds % 60print(minutes)print(rest)Show answerHide answer
SECONDS = 200MINUTES = SECONDS div 60REST = SECONDS mod 60output MINUTESoutput REST03Selection
IB selection reads like English: if CONDITION then … else if … else … end if. Every if is closed with end if.
Examples5
temp = 31if temp > 30: print("hot")TEMP = 31if TEMP > 30 then output "hot"end if3.2
If … else
The else branch runs when the condition is false. Only one of the two branches runs.
mark = 64if mark >= 50: print("pass")else: print("fail")MARK = 64if MARK >= 50 then output "pass"else output "fail"end if3.3
Else-if chain
IB has else if, so the chain stays flat with one end if at the end.
mark = 72if mark >= 80: grade = "A"elif mark >= 70: grade = "B"elif mark >= 60: grade = "C"else: grade = "U"print(grade)MARK = 72if MARK >= 80 then GRADE = "A"else if MARK >= 70 then GRADE = "B"else if MARK >= 60 then GRADE = "C"else GRADE = "U"end ifoutput GRADE3.4
Nested if
An if inside another if. Indentation shows which ELSE belongs to which IF.
age = 17hasTicket = Trueif hasTicket: if age >= 18: print("enter") else: print("adult needed")else: print("buy a ticket")AGE = 17HASTICKET = trueif HASTICKET then if AGE >= 18 then output "enter" else output "adult needed" end ifelse output "buy a ticket"end ifExercises1
Q1.Print "freezing" below 0, "cold" below 15 and "warm" otherwise.
temp = int(input("Temperature: "))if temp < 0: print("freezing")elif temp < 15: print("cold")else: print("warm")Show answerHide answer
output "Temperature: "input TEMPif TEMP < 0 then output "freezing"else if TEMP < 15 then output "cold"else output "warm"end if04Loops
IB has two loops: loop I from A to B (both ends included) and loop while CONDITION. Python range(n) stops before n, so the converter writes from 0 to N - 1. Loops with a step are written as a while loop.
Examples8
4.1
Count from 0 to n − 1
range(n) stops before n, but loop … to includes its end, so the end becomes N - 1.
n = 5for i in range(n): print(i)N = 5loop I from 0 to N - 1 output Iend loop4.2
Count with a step
IB's counting loop has no step, so a stepped loop is written as loop while with the counter updated at the end.
for i in range(0, 20, 5): print(i)I = 0loop while I < 20 output I I = I + 5end loopfor i in range(10, 0, -1): print(i)print("Lift off")I = 10loop while I > 0 output I I = I - 1end loopoutput "Lift off"4.4
While with a condition
loop while CONDITION … end loop. The condition is checked before each pass.
balance = 100years = 0while balance < 200: balance = balance * 1.1 years = years + 1print(years)BALANCE = 100YEARS = 0loop while BALANCE < 200 BALANCE = BALANCE * 1.1 YEARS = YEARS + 1end loopoutput YEARS4.5
Input validation loop
Python uses a while loop and Java a do … while. IB has no post-condition loop, so both become: read once, then loop while the value is invalid.
mark = int(input("Mark (0-100): "))while mark < 0 or mark > 100: mark = int(input("Mark (0-100): "))print(mark)output "Mark (0-100): "input MARKloop while MARK < 0 OR MARK > 100 output "Mark (0-100): " input MARKend loopoutput MARK4.6
Loop over every element of an array
IB has no for-each loop, so the converter loops over the indexes 0 to length - 1 and reads each element.
names = ["Ali", "Bea", "Cai"]for name in names: print(name)NAMES = ["Ali", "Bea", "Cai"]loop I from 0 to NAMES.length - 1 NAME = NAMES[I] output NAMEend loop4.7
Nested loops
The inner loop runs completely for every pass of the outer loop (9 outputs here).
for row in range(1, 4): for col in range(1, 4): print(row * col)loop ROW from 1 to 3 loop COL from 1 to 3 output ROW * COL end loopend loop4.8
Break / continue
Pseudocode standards have no break or continue, so they are copied and flagged. Rewrite the loop with a condition (see the linear search in Chapter 9).
nums = [4, -1, 7, 0, 3]for n in nums: if n < 0: continue if n == 0: break print(n)NUMS = [4, -1, 7, 0, 3]loop I from 0 to NUMS.length - 1 N = NUMS[I] if N < 0 then continue end if if N = 0 then break end if output Nend loop- Not directly available in IB: continue has no IB pseudocode equivalent. It was copied unchanged.
- Not directly available in IB: break has no IB pseudocode equivalent. It was copied unchanged.
Exercises2
Q1.Add up the numbers from 1 to 10 and print the total.
total = 0for i in range(1, 11): total = total + iprint(total)Show answerHide answer
TOTAL = 0loop I from 1 to 10 TOTAL = TOTAL + Iend loopoutput TOTALQ2.Keep asking for a password until the user types "open".
word = input("Password: ")while word != "open": word = input("Password: ")print("Unlocked")Show answerHide answer
output "Password: "input WORDloop while WORD ≠ "open" output "Password: " input WORDend loopoutput "Unlocked"05Arrays & lists
IB arrays look like Python lists: NAMES = ["Ali", "Bea"], indexes start at 0, and the size is NAMES.length. Lists that grow use addItem.
Examples7
scores = [12, 7, 19, 5]print(scores[0])SCORES = [12, 7, 19, 5]output SCORES[0]5.2
Fixed-size array filled with 0
[0] * 5 / new int[5] has no direct equivalent here, so it is copied and flagged. Write the list out, or fill it with a loop.
counts = [0] * 5print(counts[2])COUNTS = [0] * 5output COUNTS[2]- Not directly available in IB: List/string repetition has no IB pseudocode equivalent. It was copied unchanged.
5.3
Read and update an element
Square brackets read and write one element; the index is unchanged.
stock = [3, 8, 2]stock[1] = stock[1] - 1print(stock[1])STOCK = [3, 8, 2]STOCK[1] = STOCK[1] - 1output STOCK[1]temps = [21, 25, 19, 23]print(len(temps))TEMPS = [21, 25, 19, 23]output TEMPS.lengthtemps = [21, 25, 19, 23]last = temps[len(temps) - 1]print(last)TEMPS = [21, 25, 19, 23]LAST = TEMPS[TEMPS.length - 1]output LAST5.6
2-D array
Rows and columns are written with two pairs of brackets: GRID[row][col].
grid = [[1, 2, 3], [4, 5, 6]]grid[1][2] = 0print(grid[0][1])GRID = [[1, 2, 3], [4, 5, 6]]GRID[1][2] = 0output GRID[0][1]evens = []for i in range(1, 11): if i % 2 == 0: evens.append(i)print(evens)EVENS = []loop I from 1 to 10 if I mod 2 = 0 then EVENS.addItem(I) end ifend loopoutput EVENSExercises1
Q1.Double every value in an array, then print the first one.
values = [3, 6, 9]for i in range(len(values)): values[i] = values[i] * 2print(values[0])Show answerHide answer
VALUES = [3, 6, 9]loop I from 0 to VALUES.length - 1 VALUES[I] = VALUES[I] * 2end loopoutput VALUES[0]06Strings
IB keeps strings close to Python: .length for the length, WORD[0] for one character, and + to join.
Examples5
word = "algorithm"print(len(word))WORD = "algorithm"output WORD.lengthword = "algorithm"first = word[0]print(first)WORD = "algorithm"FIRST = WORD[0]output FIRST6.3
Upper / lower case
IB has no standard case functions, so the method call is kept as it is.
city = "Paris"print(city.upper())print(city.lower())CITY = "Paris"output CITY.upper()output CITY.lower()6.4
Compare two strings
Java must use .equals() to compare strings; in pseudocode it is an ordinary =.
password = input("Password: ")if password == "secret": print("Welcome")else: print("Wrong password")output "Password: "input PASSWORDif PASSWORD = "secret" then output "Welcome"else output "Wrong password"end if6.5
Joining strings with numbers
IB joins with +. Python's str() is kept so the number is turned into text.
name = "Sam"score = 8message = name + " scored " + str(score)print(message)NAME = "Sam"SCORE = 8MESSAGE = NAME + " scored " + str(SCORE)output MESSAGEExercises1
Q1.Ask for a word and print how many characters it has.
word = input("Word: ")print(len(word))Show answerHide answer
output "Word: "input WORDoutput WORD.length07Subprograms
IB has procedure NAME(PARAMS) … end procedure and function NAME(PARAMS) returns value … end function. A subprogram that returns something is a function.
Examples5
7.1
Procedure with a parameter
A def / void method with no return becomes procedure … end procedure; the call is just its name.
def greet(name): print("Hello " + name)greet("Kim")procedure greet(NAME) output "Hello " + NAMEend proceduregreet("Kim")7.2
Function returning a value
Returning a value makes it a function … returns value.
def area(width, height): return width * heightprint(area(4, 6))function area(WIDTH, HEIGHT) returns value return WIDTH * HEIGHTend functionoutput area(4, 6)7.3
Function with no parameters
A function with no parameters keeps its empty brackets.
def getMark(): mark = int(input("Mark: ")) return markresult = getMark()print(result)function getMark() returns value output "Mark: " input MARK return MARKend functionRESULT = getMark()output RESULT7.4
Procedure that changes an array
The array is passed in and its elements are changed in place.
def reset(nums): for i in range(len(nums)): nums[i] = 0data = [4, 5, 6]reset(data)print(data[0])procedure reset(NUMS) loop I from 0 to NUMS.length - 1 NUMS[I] = 0 end loopend procedureDATA = [4, 5, 6]reset(DATA)output DATA[0]7.5
Recursion (factorial)
A recursive function calls itself. It needs a base case (n <= 1) that stops the calls.
def factorial(n): if n <= 1: return 1 return n * factorial(n - 1)print(factorial(5))function factorial(N) returns value if N <= 1 then return 1 end if return N * factorial(N - 1)end functionoutput factorial(5)Exercises1
Q1.Write a function that returns the larger of two numbers.
def larger(a, b): if a > b: return a return bprint(larger(3, 8))Show answerHide answer
function larger(A, B) returns value if A > B then return A end if return Bend functionoutput larger(3, 8)08Random numbers
IB has no official random function; the converter keeps a RANDOM.randint(a, b) style call so the meaning is clear.
Examples1
8.1
Dice roll (1–6)
The import random line has no IB equivalent and is flagged; the randint call is kept.
import randomroll = random.randint(1, 6)print(roll)ROLL = RANDOM.randint(1, 6)output ROLLExercises1
Q1.Pick a random number from 1 to 100 and print whether it is above 50.
import randomn = random.randint(1, 100)if n > 50: print("high")else: print("low")Show answerHide answer
N = RANDOM.randint(1, 100)if N > 50 then output "high"else output "low"end if09Complete programs
These are the standard algorithms examiners ask for. Each one combines variables, loops, selection and arrays from the earlier chapters. Read the pseudocode line by line and match it to the source.
Examples5
9.1
Linear search
Checks each element in turn and stops when the target is found. A found flag in the loop condition is used instead of break.
names = ["Ali", "Bea", "Cai", "Dev"]target = input("Name: ")found = Falsei = 0while i < len(names) and not found: if names[i] == target: found = True else: i = i + 1if found: print("Found at", i)else: print("Not found")NAMES = ["Ali", "Bea", "Cai", "Dev"]output "Name: "input TARGETFOUND = falseI = 0loop while I < NAMES.length AND NOT FOUND if NAMES[I] = TARGET then FOUND = true else I = I + 1 end ifend loopif FOUND then output "Found at", Ielse output "Not found"end if9.2
Total and average
Start the total at 0, add each element, then divide by the number of elements. The average is a real number.
marks = [56, 78, 91, 64, 70]total = 0for m in marks: total = total + maverage = total / len(marks)print(total)print(average)MARKS = [56, 78, 91, 64, 70]TOTAL = 0loop I from 0 to MARKS.length - 1 M = MARKS[I] TOTAL = TOTAL + Mend loopAVERAGE = TOTAL / MARKS.lengthoutput TOTALoutput AVERAGE9.3
Maximum value
Assume the first element is the largest, then compare it with every other element.
temps = [18, 24, 21, 27, 19]highest = temps[0]for i in range(1, len(temps)): if temps[i] > highest: highest = temps[i]print(highest)TEMPS = [18, 24, 21, 27, 19]HIGHEST = TEMPS[0]loop I from 1 to TEMPS.length - 1 if TEMPS[I] > HIGHEST then HIGHEST = TEMPS[I] end ifend loopoutput HIGHEST9.4
Counting matches
A counter starts at 0 and goes up by 1 each time an element meets the condition.
marks = [45, 82, 67, 39, 90]passes = 0for m in marks: if m >= 50: passes = passes + 1print(passes)MARKS = [45, 82, 67, 39, 90]PASSES = 0loop I from 0 to MARKS.length - 1 M = MARKS[I] if M >= 50 then PASSES = PASSES + 1 end ifend loopoutput PASSES9.5
Bubble sort
Compare neighbours and swap them if they are in the wrong order. After each pass the largest remaining value is at the end, so the inner loop gets shorter.
data = [5, 2, 9, 1, 7]n = len(data)for i in range(n - 1): for j in range(n - 1 - i): if data[j] > data[j + 1]: temp = data[j] data[j] = data[j + 1] data[j + 1] = tempfor x in data: print(x)DATA = [5, 2, 9, 1, 7]N = DATA.lengthloop I from 0 to N - 2 loop J from 0 to N - 1 - I - 1 if DATA[J] > DATA[J + 1] then TEMP = DATA[J] DATA[J] = DATA[J + 1] DATA[J + 1] = TEMP end if end loopend looploop K from 0 to DATA.length - 1 X = DATA[K] output Xend loopExercises2
Q1.Find the smallest value in an array.
nums = [8, 3, 11, 5]lowest = nums[0]for i in range(1, len(nums)): if nums[i] < lowest: lowest = nums[i]print(lowest)Show answerHide answer
NUMS = [8, 3, 11, 5]LOWEST = NUMS[0]loop I from 1 to NUMS.length - 1 if NUMS[I] < LOWEST then LOWEST = NUMS[I] end ifend loopoutput LOWESTQ2.Count how many times the letter "a" appears in a word.
word = "banana"count = 0for i in range(len(word)): if word[i] == "a": count = count + 1print(count)Show answerHide answer
WORD = "banana"COUNT = 0loop I from 0 to WORD.length - 1 if WORD[I] = "a" then COUNT = COUNT + 1 end ifend loopoutput COUNT