Python → AP CSP Pseudocode
AP Computer Science Principles
Key rules
- 01Assignment uses
←; output isDISPLAY(x)and input isx ← INPUT(). - 02Loops are
REPEAT n TIMES,REPEAT UNTIL(condition)andFOR EACH item IN list; there is no counting FOR loop. - 03Lists are 1-based: the converter adds 1 to every index, so Python's names[0] becomes names[1].
- 04Subprograms are written
PROCEDURE name(params) { … }, and values are returned withRETURN(x). - 05Blocks use braces
{ }; there is no ELSE IF, so an elif chain becomes nested IF … ELSE.
Contents10 sections
Quick reference
| Concept | Python | AP CSP |
|---|---|---|
| Assignment | x = 5 | x ← 5 |
| Output | print("Hi") | DISPLAY("Hi") |
| Input | name = input() | name ← INPUT() |
| If | if x > 3: print(x) | IF(x > 3){ DISPLAY(x)} |
| Else if | if x > 3: print(1)elif x > 1: print(2) | IF(x > 3){ DISPLAY(1)}ELSE{ IF(x > 1) { DISPLAY(2) }} |
| While loop | while x < 3: x = x + 1 | REPEAT UNTIL(x ≥ 3){ x ← x + 1} |
| Counting loop | for i in range(5): print(i) | i ← 0REPEAT UNTIL(i ≥ 5){ DISPLAY(i) i ← i + 1} |
| Repeat n times | for i in range(3): print("Hi") | REPEAT 3 TIMES{ DISPLAY("Hi")} |
| For each | for x in xs: print(x) | FOR EACH x IN xs{ DISPLAY(x)} |
| Create array | xs = [4, 7, 9] | xs ← [4, 7, 9] |
| Array access | print(xs[0]) | DISPLAY(xs[1]) |
| Length | print(len(xs)) | DISPLAY(LENGTH(xs)) |
| Function + return | def twice(n): return n * 2print(twice(4)) | PROCEDURE twice(n){ RETURN(n * 2)}DISPLAY(twice(4)) |
| Procedure + call | def show(n): print(n)show(3) | PROCEDURE show(n){ DISPLAY(n)}show(3) |
| Integer division | b = a // 2 | b ← a // 2No equivalent |
| Remainder | b = a % 2 | b ← a MOD 2 |
| Not equal | print(a != 2) | DISPLAY(a ≠ 2) |
| And / or / not | print(a and not b or b) | DISPLAY(a AND NOT b OR b) |
| String join | t = s + "cd" | t ← s + "cd"No equivalent |
| Random 1–6 | r = random.randint(1, 6) | r ← RANDOM(1, 6) |
01Basics
AP CSP pseudocode uses an arrow ← for assignment so that it cannot be confused with the equality test =. Output is DISPLAY(…) and input is the expression INPUT(). Types are never written.
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
AP uses ← for assignment. Names keep the case you wrote them in.
score = 0score = score + 10score ← 0score ← score + 101.3
Variables of different types
Types are not written in AP pseudocode. Booleans are 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 ← 50DISPLAY(MAX_SIZE)total = 42print(total)total ← 42DISPLAY(total)1.6
Output text and a value
DISPLAY shows one value at a time, so print with several values becomes several DISPLAY lines. Joining with + is not part of AP pseudocode.
age = 16print("Age:", age)age ← 16DISPLAY("Age:")DISPLAY(age)1.7
Input text
INPUT() is an expression, so it appears on the right of ←. The prompt becomes a separate DISPLAY.
name = input("Enter your name: ")print("Hello " + name)DISPLAY("Enter your name: ")name ← INPUT()DISPLAY("Hello " + name)- Not directly available in AP CSP: String concatenation has no AP pseudocode equivalent. It was copied unchanged.
1.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)DISPLAY("Enter your age: ")age ← INPUT()DISPLAY(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 answerHide answer
DISPLAY("Name: ")name ← INPUT()DISPLAY("Favourite number: ")number ← INPUT()DISPLAY(name)DISPLAY(number)02Operators
AP uses MOD for remainder and the symbols ≠, ≤, ≥. It has no integer-division operator and no way to join strings with +, so those are left as they are and flagged.
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 ← 2DISPLAY(a + b)DISPLAY(a - b)DISPLAY(a * b)DISPLAY(a / b)2.2
Integer division
AP pseudocode has no integer division, so the expression is copied and flagged. Rewrite it in your answer if you need it.
minutes = 135hours = minutes // 60print(hours)minutes ← 135hours ← minutes // 60DISPLAY(hours)- Not directly available in AP CSP: Integer division (//) has no AP pseudocode equivalent. It was copied unchanged.
n = 17if n % 2 == 0: print("even")else: print("odd")n ← 17IF(n MOD 2 = 0){ DISPLAY("even")}ELSE{ DISPLAY("odd")}2.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 ** 2DISPLAY(area)- Not directly available in AP CSP: The ** operator has no AP pseudocode equivalent. It was copied unchanged.
x = 4y = 9print(x == y)print(x != y)print(x <= y)print(x >= y)x ← 4y ← 9DISPLAY(x = y)DISPLAY(x ≠ y)DISPLAY(x ≤ y)DISPLAY(x ≥ y)2.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){ DISPLAY("teen")}IF(age < 5 OR age > 65){ DISPLAY("free entry")}IF(NOT member){ DISPLAY("please register")}2.7
Joining strings
AP pseudocode has no string-joining operator, so the + is copied and flagged.
first = "Ada"last = "Lovelace"full = first + " " + lastprint(full)first ← "Ada"last ← "Lovelace"full ← first + " " + lastDISPLAY(full)- Not directly available in AP CSP: String concatenation has no AP pseudocode equivalent. It was copied unchanged.
Exercises1
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 // 60rest ← seconds MOD 60DISPLAY(minutes)DISPLAY(rest)- Not directly available in AP CSP: Integer division (//) has no AP pseudocode equivalent. It was copied unchanged.
03Selection
AP selection puts the condition in brackets and the body in braces: IF(condition) { … } ELSE { … }. There is no ELSE IF, so each extra branch is nested inside the ELSE.
Examples5
temp = 31if temp > 30: print("hot")temp ← 31IF(temp > 30){ DISPLAY("hot")}3.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){ DISPLAY("pass")}ELSE{ DISPLAY("fail")}3.3
Else-if chain
There is no else-if keyword, so each extra branch is nested inside the ELSE of the one before. Check the order of the tests: the first true branch wins.
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){ grade ← "A"}ELSE{ IF(mark ≥ 70) { grade ← "B" } ELSE { IF(mark ≥ 60) { grade ← "C" } ELSE { grade ← "U" } }}DISPLAY(grade)3.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){ IF(age ≥ 18) { DISPLAY("enter") } ELSE { DISPLAY("adult needed") }}ELSE{ DISPLAY("buy a ticket")}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 answerHide answer
DISPLAY("Temperature: ")temp ← INPUT()IF(temp < 0){ DISPLAY("freezing")}ELSE{ IF(temp < 15) { DISPLAY("cold") } ELSE { DISPLAY("warm") }}04Loops
AP has REPEAT n TIMES, REPEAT UNTIL(condition) and FOR EACH item IN list. REPEAT UNTIL stops when its condition is true, which is the opposite of while, so the condition is flipped. A counting loop that uses its counter becomes a REPEAT UNTIL with a counter variable.
Examples8
4.1
Count from 0 to n − 1
The counter is used inside the loop, so it becomes a counter variable with REPEAT UNTIL(i ≥ n). If the counter were unused you would get REPEAT n TIMES.
n = 5for i in range(n): print(i)n ← 5i ← 0REPEAT UNTIL(i ≥ n){ DISPLAY(i) i ← i + 1}4.2
Count with a step
A stepped loop becomes REPEAT UNTIL with the counter increased by the step.
for i in range(0, 20, 5): print(i)i ← 0REPEAT UNTIL(i ≥ 20){ DISPLAY(i) i ← i + 5}for i in range(10, 0, -1): print(i)print("Lift off")i ← 10REPEAT UNTIL(i ≤ 0){ DISPLAY(i) i ← i - 1}DISPLAY("Lift off")4.4
While with a condition
REPEAT UNTIL runs until its condition becomes true, so while balance < 200 becomes REPEAT UNTIL(balance ≥ 200).
balance = 100years = 0while balance < 200: balance = balance * 1.1 years = years + 1print(years)balance ← 100years ← 0REPEAT UNTIL(balance ≥ 200){ balance ← balance * 1.1 years ← years + 1}DISPLAY(years)4.5
Input validation loop
Both become REPEAT UNTIL with the opposite condition: keep asking until the value is valid.
mark = int(input("Mark (0-100): "))while mark < 0 or mark > 100: mark = int(input("Mark (0-100): "))print(mark)DISPLAY("Mark (0-100): ")mark ← INPUT()REPEAT UNTIL(NOT(mark < 0 OR mark > 100)){ DISPLAY("Mark (0-100): ") mark ← INPUT()}DISPLAY(mark)4.6
Loop over every element of an array
FOR EACH name IN names matches Python's for-in directly.
names = ["Ali", "Bea", "Cai"]for name in names: print(name)names ← ["Ali", "Bea", "Cai"]FOR EACH name IN names{ DISPLAY(name)}4.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)row ← 1REPEAT UNTIL(row ≥ 4){ col ← 1 REPEAT UNTIL(col ≥ 4) { DISPLAY(row * col) col ← col + 1 } row ← row + 1}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).
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]FOR EACH n IN nums{ IF(n < 0) { continue } IF(n = 0) { break } DISPLAY(n)}- Not directly available in AP CSP: continue has no AP pseudocode equivalent. It was copied unchanged.
- Not directly available in AP CSP: break has no AP 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 ← 0i ← 1REPEAT UNTIL(i ≥ 11){ total ← total + i i ← i + 1}DISPLAY(total)Q2.Keep asking for a password until the user types "open".
word = input("Password: ")while word != "open": word = input("Password: ")print("Unlocked")Show answerHide answer
DISPLAY("Password: ")word ← INPUT()REPEAT UNTIL(word = "open"){ DISPLAY("Password: ") word ← INPUT()}DISPLAY("Unlocked")05Arrays & lists
AP lists start at index 1, not 0. The converter shifts every index for you (names[0] → names[1], names[i] → names[i + 1]). Length is LENGTH(list) and adding uses APPEND(list, value).
Examples7
5.1
Create with values
The list literal is kept, but scores[0] becomes scores[1] because AP lists start at 1.
scores = [12, 7, 19, 5]print(scores[0])scores ← [12, 7, 19, 5]DISPLAY(scores[1])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] * 5DISPLAY(counts[3])- Not directly available in AP CSP: List/string repetition has no AP pseudocode equivalent. It was copied unchanged.
stock = [3, 8, 2]stock[1] = stock[1] - 1print(stock[1])stock ← [3, 8, 2]stock[2] ← stock[2] - 1DISPLAY(stock[2])temps = [21, 25, 19, 23]print(len(temps))temps ← [21, 25, 19, 23]DISPLAY(LENGTH(temps))5.5
Last element
Because AP lists start at 1, the last element is simply list[LENGTH(list)].
temps = [21, 25, 19, 23]last = temps[len(temps) - 1]print(last)temps ← [21, 25, 19, 23]last ← temps[LENGTH(temps)]DISPLAY(last)grid = [[1, 2, 3], [4, 5, 6]]grid[1][2] = 0print(grid[0][1])grid ← [[1, 2, 3], [4, 5, 6]]grid[2][3] ← 0DISPLAY(grid[1][2])evens = []for i in range(1, 11): if i % 2 == 0: evens.append(i)print(evens)evens ← []i ← 1REPEAT UNTIL(i ≥ 11){ IF(i MOD 2 = 0) { APPEND(evens, i) } i ← i + 1}DISPLAY(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 answerHide answer
values ← [3, 6, 9]i ← 1REPEAT UNTIL(i > LENGTH(values)){ values[i] ← values[i] * 2 i ← i + 1}DISPLAY(values[1])06Strings
AP treats a string much like a list: LENGTH(word) and word[1] for the first character (1-based). Method calls such as upper() and joining with + are not part of AP pseudocode, so they are flagged.
Examples5
word = "algorithm"print(len(word))word ← "algorithm"DISPLAY(LENGTH(word))6.2
One character
Characters are read with brackets, starting at 1, so word[0] becomes word[1].
word = "algorithm"first = word[0]print(first)word ← "algorithm"first ← word[1]DISPLAY(first)6.3
Upper / lower case
AP has no case functions, so the method calls are copied and flagged.
city = "Paris"print(city.upper())print(city.lower())city ← "Paris"DISPLAY(city.upper())DISPLAY(city.lower())- Not directly available in AP CSP: Method calls have no AP pseudocode equivalent. It was copied unchanged.
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")DISPLAY("Password: ")password ← INPUT()IF(password = "secret"){ DISPLAY("Welcome")}ELSE{ DISPLAY("Wrong password")}6.5
Joining strings with numbers
Joining and str() are not part of AP pseudocode, so they are flagged. Use separate DISPLAY calls instead.
name = "Sam"score = 8message = name + " scored " + str(score)print(message)name ← "Sam"score ← 8message ← name + " scored " + str(score)DISPLAY(message)- Not directly available in AP CSP: String concatenation has no AP pseudocode equivalent. It was copied unchanged.
- Not directly available in AP CSP: str() has no AP pseudocode equivalent. It was copied unchanged.
Exercises1
Q1.Ask for a word and print how many characters it has.
word = input("Word: ")print(len(word))Show answerHide answer
DISPLAY("Word: ")word ← INPUT()DISPLAY(LENGTH(word))07Subprograms
AP writes every subprogram as PROCEDURE name(params) { … }. A procedure that gives back a value uses RETURN(expression).
Examples5
7.1
Procedure with a parameter
The procedure body goes in braces and is called by name.
def greet(name): print("Hello " + name)greet("Kim")PROCEDURE greet(name){ DISPLAY("Hello " + name)}greet("Kim")- Not directly available in AP CSP: String concatenation has no AP pseudocode equivalent. It was copied unchanged.
def area(width, height): return width * heightprint(area(4, 6))PROCEDURE area(width, height){ RETURN(width * height)}DISPLAY(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)PROCEDURE getMark(){ DISPLAY("Mark: ") mark ← INPUT() RETURN(mark)}result ← getMark()DISPLAY(result)7.4
Procedure that changes an array
The list is passed in; its indexes are shifted to start at 1 inside the procedure too.
def reset(nums): for i in range(len(nums)): nums[i] = 0data = [4, 5, 6]reset(data)print(data[0])PROCEDURE reset(nums){ i ← 1 REPEAT UNTIL(i > LENGTH(nums)) { nums[i] ← 0 i ← i + 1 }}data ← [4, 5, 6]reset(data)DISPLAY(data[1])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))PROCEDURE factorial(n){ IF(n ≤ 1) { RETURN(1) } RETURN(n * factorial(n - 1))}DISPLAY(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
PROCEDURE larger(a, b){ IF(a > b) { RETURN(a) } RETURN(b)}DISPLAY(larger(3, 8))08Random numbers
AP has RANDOM(a, b), which gives a whole number from a to b inclusive, like Python's randint.
Examples1
8.1
Dice roll (1–6)
randint(1, 6) becomes RANDOM(1, 6). Java nextInt(6) gives 0–5, so it becomes RANDOM(0, 5) + 1.
import randomroll = random.randint(1, 6)print(roll)roll ← RANDOM(1, 6)DISPLAY(roll)Exercises1
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(1, 100)IF(n > 50){ DISPLAY("high")}ELSE{ DISPLAY("low")}09Complete programs
These are the standard algorithms examiners ask for. Watch the list indexes: the converter keeps the counter starting at 0 and adds 1 whenever it reads the list.
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"]DISPLAY("Name: ")target ← INPUT()found ← falsei ← 0REPEAT UNTIL(NOT(i < LENGTH(names) AND NOT found)){ IF(names[i + 1] = target) { found ← true } ELSE { i ← i + 1 }}IF(found){ DISPLAY("Found at") DISPLAY(i)}ELSE{ DISPLAY("Not found")}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.
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 ← 0FOR EACH m IN marks{ total ← total + m}average ← total / LENGTH(marks)DISPLAY(total)DISPLAY(average)9.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[1]i ← 1REPEAT UNTIL(i ≥ LENGTH(temps)){ IF(temps[i + 1] > highest) { highest ← temps[i + 1] } i ← i + 1}DISPLAY(highest)9.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 ← 0FOR EACH m IN marks{ IF(m ≥ 50) { passes ← passes + 1 }}DISPLAY(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.
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 ← LENGTH(data)i ← 0REPEAT UNTIL(i ≥ n - 1){ j ← 0 REPEAT UNTIL(j ≥ n - 1 - i) { IF(data[j + 1] > data[j + 2]) { temp ← data[j + 1] data[j + 1] ← data[j + 2] data[j + 2] ← temp } j ← j + 1 } i ← i + 1}FOR EACH x IN data{ DISPLAY(x)}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 answerHide answer
nums ← [8, 3, 11, 5]lowest ← nums[1]i ← 1REPEAT UNTIL(i ≥ LENGTH(nums)){ IF(nums[i + 1] < lowest) { lowest ← nums[i + 1] } i ← i + 1}DISPLAY(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 answerHide answer
word ← "banana"count ← 0i ← 1REPEAT UNTIL(i > LENGTH(word)){ IF(word[i] = "a") { count ← count + 1 } i ← i + 1}DISPLAY(count)