Skip to content
Pseudocode Converter

Python → IB Pseudocode

IB Computer Science

Key rules

  1. 01Variable names are written in CAPITALS (SCORE, TOTAL); subprogram names keep their case.
  2. 02Assignment uses =, and printing uses output; reading a value uses input NAME.
  3. 03Counting loops are loop I from A to B, where both ends are included, so range(n) becomes 0 to N - 1.
  4. 04Selection is if … then … else if … else … end if.
  5. 05Arrays are 0-based like Python and Java, and their size is ARRAY.length.
Contents10 sections
  1. —Quick reference
  2. 01Basics
  3. 02Operators
  4. 03Selection
  5. 04Loops
  6. 05Arrays & lists
  7. 06Strings
  8. 07Subprograms
  9. 08Random numbers
  10. 09Complete programs

Quick reference

ConceptPythonIB
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 * 2​print(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.

Python
# Calculate the area of a rectanglearea = 4 * 3
IB
// Calculate the area of a rectangleAREA = 4 * 3

1.2

Assign a variable

IB uses = for assignment and CAPITAL names. Updating a variable is written in full (SCORE = SCORE + 10).

Python
score = 0score = score + 10
IB
SCORE = 0SCORE = SCORE + 10

1.3

Variables of different types

Types are not written in IB pseudocode. Booleans are lower-case true / false.

Python
count = 5price = 2.75name = "Ana"found = False
IB
COUNT = 5PRICE = 2.75NAME = "Ana"FOUND = false

1.4

Constant

There is no constant keyword, so a constant is just a variable written in capitals that you never change.

Python
MAX_SIZE = 50print(MAX_SIZE)
IB
MAX_SIZE = 50output MAX_SIZE

1.5

Output a value

Printing becomes output.

Python
total = 42print(total)
IB
TOTAL = 42output TOTAL

1.6

Output text and a value

Several values can be listed after output, separated by commas.

Python
age = 16print("Age:", age)
IB
AGE = 16output "Age:", AGE

1.7

Input text

A prompt becomes its own output line, followed by input NAME.

Python
name = input("Enter your name: ")print("Hello " + name)
IB
output "Enter your name: "input NAMEoutput "Hello " + NAME

1.8

Input a number

Converting the input with int() (or sc.nextInt()) is not written in pseudocode; input simply reads a value.

Python
age = int(input("Enter your age: "))print(age + 1)
IB
output "Enter your age: "input AGEoutput AGE + 1

Exercises1

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 answer
Answer
output "Name: "input NAMEoutput "Favourite number: "input NUMBERoutput NAME, NUMBER

02Operators

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.

Python
a = 7b = 2print(a + b)print(a - b)print(a * b)print(a / b)
IB
A = 7B = 2output A + Boutput A - Boutput A * Boutput A / B

2.2

Integer division

Python // and Java / between two ints both become div.

Python
minutes = 135hours = minutes // 60print(hours)
IB
MINUTES = 135HOURS = MINUTES div 60output HOURS

2.3

Remainder (modulo)

% becomes mod. Testing mod 2 = 0 is the usual way to check for an even number.

Python
n = 17if n % 2 == 0:    print("even")else:    print("odd")
IB
N = 17if N mod 2 = 0 then    output "even"else    output "odd"end if

2.4

Power

This standard has no power operator, so the expression is copied and flagged. Multiply instead (side * side).

Python
side = 5area = side ** 2print(area)
IB
SIDE = 5AREA = side ** 2output AREA
  • Not directly available in IB: The ** operator has no IB pseudocode equivalent. It was copied unchanged.

2.5

Comparisons

Equality is a single =; not-equal is ≠.

Python
x = 4y = 9print(x == y)print(x != y)print(x <= y)print(x >= y)
IB
X = 4Y = 9output X = Youtput X ≠ Youtput X <= Youtput X >= Y

2.6

Logical and / or / not

Java &&, ||, ! and Python and, or, not all become the capitalised words AND, OR, NOT.

Python
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")
IB
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 if

2.7

Joining strings

IB joins strings with +.

Python
first = "Ada"last = "Lovelace"full = first + " " + lastprint(full)
IB
FIRST = "Ada"LAST = "Lovelace"FULL = FIRST + " " + LASToutput FULL

Exercises1

Q1.Convert a number of seconds into minutes and remaining seconds.

seconds = 200minutes = seconds // 60rest = seconds % 60print(minutes)print(rest)
Show answer
Answer
SECONDS = 200MINUTES = SECONDS div 60REST = SECONDS mod 60output MINUTESoutput REST

03Selection

IB selection reads like English: if CONDITION then … else if … else … end if. Every if is closed with end if.

Examples5

3.1

If

if … then … end if.

Python
temp = 31if temp > 30:    print("hot")
IB
TEMP = 31if TEMP > 30 then    output "hot"end if

3.2

If … else

The else branch runs when the condition is false. Only one of the two branches runs.

Python
mark = 64if mark >= 50:    print("pass")else:    print("fail")
IB
MARK = 64if MARK >= 50 then    output "pass"else    output "fail"end if

3.3

Else-if chain

IB has else if, so the chain stays flat with one end if at the end.

Python
mark = 72if mark >= 80:    grade = "A"elif mark >= 70:    grade = "B"elif mark >= 60:    grade = "C"else:    grade = "U"print(grade)
IB
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 GRADE

3.4

Nested if

An if inside another if. Indentation shows which ELSE belongs to which IF.

Python
age = 17hasTicket = Trueif hasTicket:    if age >= 18:        print("enter")    else:        print("adult needed")else:    print("buy a ticket")
IB
AGE = 17HASTICKET = trueif HASTICKET then    if AGE >= 18 then        output "enter"    else        output "adult needed"    end ifelse    output "buy a ticket"end if

Exercises1

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 answer
Answer
output "Temperature: "input TEMPif TEMP < 0 then    output "freezing"else if TEMP < 15 then    output "cold"else    output "warm"end if

04Loops

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.

Python
n = 5for i in range(n):    print(i)
IB
N = 5loop I from 0 to N - 1    output Iend loop

4.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.

Python
for i in range(0, 20, 5):    print(i)
IB
I = 0loop while I < 20    output I    I = I + 5end loop

4.3

Count down

Counting down is written as a while loop that subtracts 1.

Python
for i in range(10, 0, -1):    print(i)print("Lift off")
IB
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.

Python
balance = 100years = 0while balance < 200:    balance = balance * 1.1    years = years + 1print(years)
IB
BALANCE = 100YEARS = 0loop while BALANCE < 200    BALANCE = BALANCE * 1.1    YEARS = YEARS + 1end loopoutput YEARS

4.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.

Python
mark = int(input("Mark (0-100): "))while mark < 0 or mark > 100:    mark = int(input("Mark (0-100): "))print(mark)
IB
output "Mark (0-100): "input MARKloop while MARK < 0 OR MARK > 100    output "Mark (0-100): "    input MARKend loopoutput MARK

4.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.

Python
names = ["Ali", "Bea", "Cai"]for name in names:    print(name)
IB
NAMES = ["Ali", "Bea", "Cai"]loop I from 0 to NAMES.length - 1    NAME = NAMES[I]    output NAMEend loop

4.7

Nested loops

The inner loop runs completely for every pass of the outer loop (9 outputs here).

Python
for row in range(1, 4):    for col in range(1, 4):        print(row * col)
IB
loop ROW from 1 to 3    loop COL from 1 to 3        output ROW * COL    end loopend loop

4.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).

Python
nums = [4, -1, 7, 0, 3]for n in nums:    if n < 0:        continue    if n == 0:        break    print(n)
IB
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 answer
Answer
TOTAL = 0loop I from 1 to 10    TOTAL = TOTAL + Iend loopoutput TOTAL

Q2.Keep asking for a password until the user types "open".

word = input("Password: ")while word != "open":    word = input("Password: ")print("Unlocked")
Show answer
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

5.1

Create with values

The list literal is kept, and index 0 is the first element.

Python
scores = [12, 7, 19, 5]print(scores[0])
IB
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.

Python
counts = [0] * 5print(counts[2])
IB
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.

Python
stock = [3, 8, 2]stock[1] = stock[1] - 1print(stock[1])
IB
STOCK = [3, 8, 2]STOCK[1] = STOCK[1] - 1output STOCK[1]

5.4

Length

len() and .length both become .length.

Python
temps = [21, 25, 19, 23]print(len(temps))
IB
TEMPS = [21, 25, 19, 23]output TEMPS.length

5.5

Last element

The last index is length - 1 because indexes start at 0.

Python
temps = [21, 25, 19, 23]last = temps[len(temps) - 1]print(last)
IB
TEMPS = [21, 25, 19, 23]LAST = TEMPS[TEMPS.length - 1]output LAST

5.6

2-D array

Rows and columns are written with two pairs of brackets: GRID[row][col].

Python
grid = [[1, 2, 3], [4, 5, 6]]grid[1][2] = 0print(grid[0][1])
IB
GRID = [[1, 2, 3], [4, 5, 6]]GRID[1][2] = 0output GRID[0][1]

5.7

Add to a list

IB collections that grow use addItem.

Python
evens = []for i in range(1, 11):    if i % 2 == 0:        evens.append(i)print(evens)
IB
EVENS = []loop I from 1 to 10    if I mod 2 = 0 then        EVENS.addItem(I)    end ifend loopoutput EVENS

Exercises1

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 answer
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

6.1

Length

len(word) / word.length() becomes WORD.length.

Python
word = "algorithm"print(len(word))
IB
WORD = "algorithm"output WORD.length

6.2

One character

Characters are read with brackets, starting at 0.

Python
word = "algorithm"first = word[0]print(first)
IB
WORD = "algorithm"FIRST = WORD[0]output FIRST

6.3

Upper / lower case

IB has no standard case functions, so the method call is kept as it is.

Python
city = "Paris"print(city.upper())print(city.lower())
IB
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 =.

Python
password = input("Password: ")if password == "secret":    print("Welcome")else:    print("Wrong password")
IB
output "Password: "input PASSWORDif PASSWORD = "secret" then    output "Welcome"else    output "Wrong password"end if

6.5

Joining strings with numbers

IB joins with +. Python's str() is kept so the number is turned into text.

Python
name = "Sam"score = 8message = name + " scored " + str(score)print(message)
IB
NAME = "Sam"SCORE = 8MESSAGE = NAME + " scored " + str(SCORE)output MESSAGE

Exercises1

Q1.Ask for a word and print how many characters it has.

word = input("Word: ")print(len(word))
Show answer
Answer
output "Word: "input WORDoutput WORD.length

07Subprograms

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.

Python
def greet(name):    print("Hello " + name)​greet("Kim")
IB
procedure greet(NAME)    output "Hello " + NAMEend proceduregreet("Kim")

7.2

Function returning a value

Returning a value makes it a function … returns value.

Python
def area(width, height):    return width * height​print(area(4, 6))
IB
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.

Python
def getMark():    mark = int(input("Mark: "))    return mark​result = getMark()print(result)
IB
function getMark() returns value    output "Mark: "    input MARK    return MARKend functionRESULT = getMark()output RESULT

7.4

Procedure that changes an array

The array is passed in and its elements are changed in place.

Python
def reset(nums):    for i in range(len(nums)):        nums[i] = 0​data = [4, 5, 6]reset(data)print(data[0])
IB
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.

Python
def factorial(n):    if n <= 1:        return 1    return n * factorial(n - 1)​print(factorial(5))
IB
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 b​print(larger(3, 8))
Show answer
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.

Python
import random​roll = random.randint(1, 6)print(roll)
IB
ROLL = RANDOM.randint(1, 6)output ROLL

Exercises1

Q1.Pick a random number from 1 to 100 and print whether it is above 50.

import random​n = random.randint(1, 100)if n > 50:    print("high")else:    print("low")
Show answer
Answer
N = RANDOM.randint(1, 100)if N > 50 then    output "high"else    output "low"end if

09Complete 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.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.

Python
marks = [56, 78, 91, 64, 70]total = 0for m in marks:    total = total + maverage = total / len(marks)print(total)print(average)
IB
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 AVERAGE

9.3

Maximum value

Assume the first element is the largest, then compare it with every other element.

Python
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)
IB
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 HIGHEST

9.4

Counting matches

A counter starts at 0 and goes up by 1 each time an element meets the condition.

Python
marks = [45, 82, 67, 39, 90]passes = 0for m in marks:    if m >= 50:        passes = passes + 1print(passes)
IB
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 PASSES

9.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.

Python
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)
IB
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 loop

Exercises2

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 answer
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 LOWEST

Q2.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 answer
Answer
WORD = "banana"COUNT = 0loop I from 0 to WORD.length - 1    if WORD[I] = "a" then        COUNT = COUNT + 1    end ifend loopoutput COUNT