Pseudocode ↔ Python
Every construct from the Cambridge pseudocode guide, with the Python you'd write in Paper 4. Filter for your syllabus and bookmark this. Try any snippet in the Playground → — complete Python programs have a Run Python button that opens them in the Python Playground.
Source: Cambridge 9618 Pseudocode Guide for Teachers — For examination in 2027, 2028 and 2029
Pseudocode string manipulation functions will always be provided in examinations (§5.5). Any pseudocode functions used in an examination will be defined (§8).
Changes this year: 2026 → 2027–29: no changes to syntax or functions. Only fix: the Cat class example in §10.2 now declares Breed : STRING (was INTEGER).
37 constructs. Badges mark the ones that belong to one syllabus only.
§1 How pseudocode appears in the exam §1.1–1.5
Monospaced font, three-space indentation, keywords in UPPER CASE, identifiers in MixedCase, meta-variables in <angle brackets>. Comments start with // and run to the end of the line.
CAIE pseudocode// this procedure swaps// values of X and YPROCEDURE SWAP(BYREF X : INTEGER, Y : INTEGER)DECLARE Temp : INTEGERTemp ← X // temporarily store XX ← YY ← TempENDPROCEDURE
Python# this procedure swaps
# values of x and y
def swap(x, y):
return y, x💡 Note the guide: when several parameters use the same method, BYREF need not be repeated — here Y is also BYREF. The guide leaves Temp undeclared; the Playground (like an examiner) expects the DECLARE.
Meta-variables (§1.3)
Run PythonCAIE pseudocodeREPEAT<statement(s)>UNTIL <condition>
Python# <…> means “substitute something here”💡 Angle brackets are never typed in real code — they show where your own statements/conditions go.
§2 Variables, constants & data types §2.1–2.6
Six basic types: INTEGER, REAL, CHAR, STRING, BOOLEAN, DATE. Declare before use. Identifiers: letters, digits, underscore; start with a letter; case-insensitive. Assignment is ←.
CAIE pseudocodeDECLARE Count : INTEGER // 5, -3DECLARE Price : REAL // 4.7, 0.3, -4.0 (a digit each side of the point)DECLARE Grade : CHAR // 'x', 'C', '@' (single quotes)DECLARE Name : STRING // "This is a string", "" (double quotes)DECLARE Found : BOOLEAN // TRUE, FALSEDECLARE DOB : DATE // 02/01/2005 (dd/mm/yyyy)Count ← -3Price ← 4.7Grade ← 'C'Name ← ""Found ← TRUEDOB ← 02/01/2005OUTPUT Count, " ", Price, " ", Grade, " ", Found, " ", DOB
Pythoncount = -3
price = 4.7
grade = 'C'
name = ""
found = True
from datetime import date
dob = date(2005, 1, 2)💡 DATE is a 9618 type only — 2210 has just INTEGER, REAL, CHAR, STRING and BOOLEAN.
CAIE pseudocodeDECLARE Counter : INTEGERDECLARE TotalToPay : REALDECLARE GameOver : BOOLEAN
Pythoncounter: int = 0
total_to_pay: float = 0.0
game_over: bool = False💡 Format: DECLARE <identifier> : <data type>. In 9618 you are expected to declare every variable.
CAIE pseudocodeCONSTANT HourlyRate = 6.50CONSTANT DefaultText = "N/A"OUTPUT HourlyRate * 40, " ", DefaultText
PythonHOURLY_RATE = 6.50
DEFAULT_TEXT = "N/A"💡 Only a literal may be the value of a constant — never a variable, another constant or an expression. (The Playground enforces this.)
CAIE pseudocodeDECLARE Counter, NumberOfHours : INTEGERDECLARE TotalToPay : REALCONSTANT HourlyRate = 6.50Counter ← 0Counter ← Counter + 1NumberOfHours ← 12TotalToPay ← NumberOfHours * HourlyRateOUTPUT Counter, " ", TotalToPay
Pythoncounter = 0
counter = counter + 1
total_to_pay = number_of_hours * HOURLY_RATE💡 The operator is ← (you may write <- in exams). A single = is comparison, not assignment.
§3 Arrays §3.1–3.2
Fixed-length, one data type, consecutive indices. State the lower bound explicitly — usually 1. Two-dimensional arrays use two ranges.
CAIE pseudocodeDECLARE StudentNames : ARRAY[1:30] OF STRINGDECLARE NoughtsAndCrosses : ARRAY[1:3,1:3] OF CHAR
Pythonstudent_names = [""] * 30
noughts_and_crosses = [[' '] * 3 for _ in range(3)]💡 Python lists start at 0, so StudentNames[1] ↔ student_names[0].
CAIE pseudocodeDECLARE StudentNames : ARRAY[1:30] OF STRINGDECLARE NoughtsAndCrosses : ARRAY[1:3,1:3] OF CHARDECLARE n : INTEGERn ← 1StudentNames[1] ← "Ali"NoughtsAndCrosses[2,3] ← 'X'StudentNames[n+1] ← StudentNames[n]OUTPUT StudentNames[2], " ", NoughtsAndCrosses[2,3]
Pythonstudent_names[0] = "Ali"
noughts_and_crosses[1][2] = 'X'
student_names[n] = student_names[n - 1]CAIE pseudocodeDECLARE StudentNames : ARRAY[1:30] OF STRINGDECLARE Backup : ARRAY[1:30] OF STRINGDECLARE Index : INTEGERFOR Index ← 1 TO 30StudentNames[Index] ← ""NEXT IndexStudentNames[7] ← "Sara"Backup ← StudentNames // allowed: same size and typeOUTPUT Backup[7]
Pythonstudent_names = [""] * 30
backup = student_names.copy()💡 Do NOT write StudentNames[1 TO 30] ← "" — the guide says to use a loop instead.
§4 User-defined data types §4.1–4.2
Non-composite: enumerated and pointer. Composite: record, set, class/object (§10). ADTs (stack, queue, linked list, dictionary, binary tree) are built from these.
CAIE pseudocodeTYPE Season = (Spring, Summer, Autumn, Winter)DECLARE ThisSeason, NextSeason : SeasonThisSeason ← SpringNextSeason ← ThisSeason + 1OUTPUT NextSeason
Pythonfrom enum import Enum
class Season(Enum):
SPRING = 1; SUMMER = 2; AUTUMN = 3; WINTER = 4
this_season = Season.SPRING
next_season = Season(this_season.value + 1)💡 Values have an order, so + 1 moves to the next value and < > comparisons work.
Pointer type (§4.1) — ^ declares, ^Var takes the address, Ptr^ dereferences
9618 only Run Run Python VB.NET · JavaCAIE pseudocodeTYPE TIntPointer = ^INTEGERDECLARE MyPointer : TIntPointerDECLARE Count : INTEGERCount ← 5MyPointer ← ^Count // address of CountMyPointer^ ← MyPointer^ + 1 // access the value stored at the memory addressOUTPUT Count
Python# Python has no raw pointers; the closest idea is
# two names bound to one mutable object.
count = [5]
my_pointer = count
my_pointer[0] += 1
print(count[0])💡 Declaring the pointer VARIABLE does not use ^ — only the TYPE definition, the address-of and the dereference do.
CAIE pseudocodeTYPE StudentRecordDECLARE LastName : STRINGDECLARE FirstName : STRINGDECLARE DateOfBirth : DATEDECLARE YearGroup : INTEGERDECLARE FormGroup : CHARENDTYPEDECLARE Pupil1, Pupil2 : StudentRecordPupil1.LastName ← "Johnson"Pupil1.FirstName ← "Leroy"Pupil1.DateOfBirth ← 02/01/2005Pupil1.YearGroup ← 6Pupil1.FormGroup ← 'A'Pupil2 ← Pupil1OUTPUT Pupil2.FirstName, " ", Pupil2.LastName
Pythonfrom dataclasses import dataclass
from datetime import date
@dataclass
class StudentRecord:
last_name: str = ""
first_name: str = ""
date_of_birth: date = date(2000, 1, 1)
year_group: int = 0
form_group: str = ""
pupil1 = StudentRecord("Johnson", "Leroy", date(2005, 1, 2), 6, 'A')
import copy; pupil2 = copy.copy(pupil1)CAIE pseudocodeTYPE StudentRecordDECLARE LastName : STRINGDECLARE YearGroup : INTEGERENDTYPEDECLARE Form : ARRAY[1:30] OF StudentRecordDECLARE Index : INTEGERFOR Index ← 1 TO 30 // every field must be given a value before it is readForm[Index].YearGroup ← 7NEXT IndexFOR Index ← 1 TO 30Form[Index].YearGroup ← Form[Index].YearGroup + 1NEXT IndexOUTPUT Form[30].YearGroup
Pythonform = [StudentRecord() for _ in range(30)]
for s in form:
s.year_group += 1CAIE pseudocodeTYPE LetterSet = SET OF CHARDEFINE Vowels ('A','E','I','O','U') : LetterSetDECLARE Ch : CHARCh ← 'E'IF Ch IN Vowels THENOUTPUT Ch, " is a vowel"ENDIF
Pythonvowels = {'A', 'E', 'I', 'O', 'U'}
if ch in vowels:
print(ch, "is a vowel")💡 The guide defines only the declaration (TYPE … = SET OF …, DEFINE …). IN is a Playground convenience for membership.
§5 Common operations §5.1–5.6
INPUT/OUTPUT, arithmetic (+ − * / DIV MOD), relational (> < >= <= = <>), logic (AND OR NOT), the string functions the exam will always provide, and INT / RAND.
CAIE pseudocodeDECLARE Answer : STRINGDECLARE Score, Lives : INTEGERScore ← 120Lives ← 3INPUT AnswerOUTPUT ScoreOUTPUT "You have ", Lives, " lives left"
Pythonanswer = input()
print(score)
print("You have", lives, "lives left")💡 Several values separated by commas can be output in one statement.
CAIE pseudocodeOUTPUT 7 / 2 // 3.5 (REAL even for integer operands)OUTPUT 7 DIV 2 // 3 (quotient)OUTPUT 7 MOD 2 // 1 (remainder)OUTPUT (2 + 3) * 4 // use brackets to make order explicit
Pythonprint(7 / 2) # 3.5
print(7 // 2) # 3
print(7 % 2) # 1
print((2 + 3) * 4)CAIE pseudocodeDECLARE A, B : INTEGERA ← 5B ← 8OUTPUT A > B, " ", A <= B, " ", A = 5, " ", A <> BOUTPUT (A < B) AND NOT (B = 8)OUTPUT (A > B) OR (B > A)
Pythonprint(a > b, a <= b, a == 5, a != b)
print((a < b) and not (b == 8))
print((a > b) or (b > a))💡 Results are always BOOLEAN. Only AND, OR, NOT are used.
CAIE pseudocodeOUTPUT RIGHT("ABCDEFGH", 3) // "FGH"OUTPUT LENGTH("Happy Days") // 10OUTPUT MID("ABCDEFGH", 2, 3) // "BCD" (start position, length)OUTPUT LCASE('W') // 'w'OUTPUT UCASE('h') // 'H'OUTPUT "Summer" & " " & "Pudding" // & concatenates
Python"ABCDEFGH"[-3:] # RIGHT
len("Happy Days") # LENGTH
"ABCDEFGH"[1:4] # MID(s, 2, 3) → start index 1, length 3
'W'.lower(); 'h'.upper()
"Summer" + " " + "Pudding"💡 These are the ONLY string functions defined in the 9618 guide. LCASE/UCASE take a CHAR; a non-letter is returned unchanged. 2210 additionally uses LEFT, SUBSTRING and applies UCASE/LCASE to strings.
CAIE pseudocodeOUTPUT INT(27.5415) // 27 — the integer partOUTPUT RAND(87) < 87 // RAND(x): random REAL from 0 up to (not including) xOUTPUT INT(RAND(6)) + 1 // a dice roll 1–6
Pythonint(27.5415)
import random
random.random() * 87
random.randint(1, 6)💡 2210 uses ROUND(x, places) and RANDOM() instead — both also run in the Playground.
§6 Selection §6.1–6.2
IF … THEN … [ELSE …] ENDIF and CASE OF … [OTHERWISE …] ENDCASE. There is no ELSEIF — nest IFs.
CAIE pseudocodeDECLARE ChallengerScore, ChampionScore, HighestScore : INTEGERDECLARE ChallengerName, ChampionName : STRINGChallengerScore ← 90ChampionScore ← 85HighestScore ← 95ChallengerName ← "Ayesha"ChampionName ← "Bilal"IF ChallengerScore > ChampionScore THENIF ChallengerScore > HighestScore THENOUTPUT ChallengerName, " is champion and highest scorer"ELSEOUTPUT ChallengerName, " is the new champion"ENDIFELSEOUTPUT ChampionName, " is still the champion"IF ChampionScore > HighestScore THENOUTPUT ChampionName, " is also the highest scorer"ENDIFENDIF
Pythonif challenger_score > champion_score:
if challenger_score > highest_score:
print(challenger_name, "is champion and highest scorer")
else:
print(challenger_name, "is the new champion")
else:
print(champion_name, "is still the champion")
if champion_score > highest_score:
print(champion_name, "is also the highest scorer")CAIE pseudocodeDECLARE Move : CHARDECLARE Position : INTEGERPosition ← 50INPUT MoveCASE OF Move'W' : Position ← Position - 10'S' : Position ← Position + 10'A' : Position ← Position - 1'D' : Position ← Position + 1OTHERWISE : OUTPUT "Beep"ENDCASEOUTPUT Position
Pythonmatch move:
case 'W': position -= 10
case 'S': position += 10
case 'A': position -= 1
case 'D': position += 1
case _: print("Beep")💡 Cases are tested in sequence; the first that applies runs and control goes to after ENDCASE. OTHERWISE must be last.
CAIE pseudocodeDECLARE Mark : INTEGERMark ← 67CASE OF Mark80 TO 100 : OUTPUT "A"60 TO 79 : OUTPUT "B"40 TO 59 : OUTPUT "C"OTHERWISE : OUTPUT "U"ENDCASE
Pythonif 80 <= mark <= 100: print("A")
elif 60 <= mark <= 79: print("B")
elif 40 <= mark <= 59: print("C")
else: print("U")§7 Iteration §7.1–7.3
Count-controlled FOR … NEXT (inclusive, optional STEP), post-condition REPEAT … UNTIL (runs at least once), pre-condition WHILE … ENDWHILE (may run zero times).
CAIE pseudocodeCONSTANT MaxRow = 3DECLARE Amount : ARRAY[1:3, 1:10] OF INTEGERDECLARE Row, Column, RowTotal, Total : INTEGERFOR Row ← 1 TO MaxRowFOR Column ← 1 TO 10Amount[Row, Column] ← Row * ColumnNEXT ColumnNEXT RowTotal ← 0FOR Row ← 1 TO MaxRowRowTotal ← 0FOR Column ← 1 TO 10RowTotal ← RowTotal + Amount[Row, Column]NEXT ColumnOUTPUT "Total for Row ", Row, " is ", RowTotalTotal ← Total + RowTotalNEXT RowOUTPUT "The grand total is ", Total
Pythontotal = 0
for row in range(MAX_ROW):
row_total = 0
for column in range(10):
row_total += amount[row][column]
print("Total for Row", row + 1, "is", row_total)
total += row_total
print("The grand total is", total)💡 If value1 = value2 the body runs once; if value1 > value2 it does not run at all. Repeat the identifier after NEXT.
CAIE pseudocodeDECLARE i : INTEGERFOR i ← 10 TO 1 STEP -3OUTPUT iNEXT i
Pythonfor i in range(10, 0, -3):
print(i)💡 The loop ends when the counter goes past value2. STEP may be negative.
CAIE pseudocodeDECLARE Password : STRINGREPEATOUTPUT "Please enter the password"INPUT PasswordUNTIL Password = "Secret"OUTPUT "Welcome"
Pythonwhile True:
print("Please enter the password")
password = input()
if password == "Secret":
break💡 Statements run at least once; the condition is tested afterwards and TRUE ends the loop.
CAIE pseudocodeDECLARE Number : INTEGERNumber ← 25WHILE Number > 9Number ← Number - 9ENDWHILEOUTPUT Number
Pythonwhile number > 9:
number = number - 9💡 9618 writes WHILE <condition> with no DO (2210 writes WHILE <condition> DO). Both run in the Playground.
§8 Procedures & functions §8.1–8.3
Procedures are CALLed as complete statements; functions RETURN a value and are used inside expressions (never with CALL). Parameters are BYVAL unless BYREF is stated. Functions must not take BYREF parameters.
CAIE pseudocodeCONSTANT Default = 100DECLARE Size : INTEGERPROCEDURE MoveForward(Distance : INTEGER)OUTPUT "forward ", DistanceENDPROCEDUREPROCEDURE Turn(Angle : INTEGER)OUTPUT "turn ", AngleENDPROCEDUREPROCEDURE Square(Size : INTEGER)DECLARE Side : INTEGERFOR Side ← 1 TO 4CALL MoveForward(Size)CALL Turn(90)NEXT SideENDPROCEDUREPROCEDURE DefaultSquare()CALL Square(100)ENDPROCEDURESize ← 50IF Size = Default THENCALL DefaultSquare()ELSECALL Square(Size)ENDIF
Pythondef square(size):
for side in range(4):
move_forward(size)
turn(90)
def default_square():
square(100)
if size == DEFAULT:
default_square()
else:
square(size)CAIE pseudocodeDECLARE Distance : INTEGERDistance ← 7FUNCTION Max(Number1 : INTEGER, Number2 : INTEGER) RETURNS INTEGERIF Number1 > Number2 THENRETURN Number1ELSERETURN Number2ENDIFENDFUNCTIONOUTPUT "Penalty Fine = ", Max(10, Distance*2)
Pythondef max_(number1, number2):
if number1 > number2:
return number1
return number2
print("Penalty Fine =", max_(10, distance * 2))💡 RETURN executes immediately — later lines in the function are skipped. Do not write CALL before a function.
CAIE pseudocodePROCEDURE SWAP(BYREF X : INTEGER, Y : INTEGER)DECLARE Temp : INTEGERTemp ← XX ← YY ← TempENDPROCEDUREDECLARE A, B : INTEGERA ← 1B ← 2CALL SWAP(A, B)OUTPUT A, " ", B
Python# Python passes references to objects; ints are immutable,
# so return the new values instead:
def swap(x, y):
return y, x
a, b = swap(a, b)💡 BYREF: the procedure changes the caller's variable. BYVAL (the default): it works on a copy. One BYREF keyword covers the following parameters passed the same way.
§9 File handling §9.1–9.2
Text files: OPENFILE … FOR READ | WRITE | APPEND, READFILE, WRITEFILE, EOF, CLOSEFILE. Random files: OPENFILE … FOR RANDOM, SEEK, GETRECORD, PUTRECORD.
CAIE pseudocodeDECLARE LineOfText : STRING// make FileA.txt firstOPENFILE "FileA.txt" FOR WRITEWRITEFILE "FileA.txt", "first line"WRITEFILE "FileA.txt", ""WRITEFILE "FileA.txt", "third line"CLOSEFILE "FileA.txt"OPENFILE "FileA.txt" FOR READOPENFILE "FileB.txt" FOR WRITEWHILE NOT EOF("FileA.txt")READFILE "FileA.txt", LineOfTextIF LineOfText = "" THENWRITEFILE "FileB.txt", " ----------------------------"ELSEWRITEFILE "FileB.txt", LineOfTextENDIFENDWHILECLOSEFILE "FileA.txt"CLOSEFILE "FileB.txt"OUTPUT "copied — see the Files panel"
Pythonwith open("FileA.txt") as src, open("FileB.txt", "w") as dst:
for line in src:
line = line.rstrip("\n")
dst.write((" " + "-" * 28 if line == "" else line) + "\n")💡 WRITE creates a new file (existing data lost); APPEND adds after existing data. EOF(file) is TRUE when no lines remain. Open a file in one mode at a time.
CAIE pseudocodeTYPE StudentDECLARE LastName : STRINGDECLARE YearGroup : INTEGERENDTYPEDECLARE Pupil, NewPupil : StudentDECLARE Position : INTEGEROPENFILE "StudentFile.Dat" FOR RANDOMFOR Position ← 10 TO 12Pupil.LastName ← "Pupil" & NUM_TO_STR(Position)Pupil.YearGroup ← 6SEEK "StudentFile.Dat", PositionPUTRECORD "StudentFile.Dat", PupilNEXT Position// move records 12..10 up one place, then insert at 10FOR Position ← 12 TO 10 STEP -1SEEK "StudentFile.Dat", PositionGETRECORD "StudentFile.Dat", PupilSEEK "StudentFile.Dat", Position + 1PUTRECORD "StudentFile.Dat", PupilNEXT PositionNewPupil.LastName ← "Johnson"NewPupil.YearGroup ← 6SEEK "StudentFile.Dat", 10PUTRECORD "StudentFile.Dat", NewPupilCLOSEFILE "StudentFile.Dat"OUTPUT "done — see the Files panel"
Pythonimport pickle, os
# Python: use a fixed record size and f.seek(pos * SIZE)
# with struct/pickle, or a shelve/dbm for keyed records.💡 SEEK moves the file pointer to a record address; GETRECORD reads the record there into a variable of the right type; PUTRECORD overwrites the record there.
§10 Object-oriented programming §10.1–10.2
Methods and properties are public unless stated; PUBLIC/PRIVATE are used when access matters. Constructors are procedures named NEW. INHERITS for subclasses; SUPER for the parent's methods; NEW <class>(…) creates an object.
CAIE pseudocodeCLASS PlayerClassPRIVATE Attempts : INTEGERPUBLIC PROCEDURE NEW()Attempts ← 3ENDPROCEDUREPUBLIC PROCEDURE SetAttempts(Number : INTEGER)Attempts ← NumberENDPROCEDUREPUBLIC FUNCTION GetAttempts() RETURNS INTEGERRETURN AttemptsENDFUNCTIONENDCLASSDECLARE Player : PlayerClassPlayer ← NEW PlayerClass()Player.SetAttempts(5)OUTPUT Player.GetAttempts()
Pythonclass Player:
def __init__(self):
self.__attempts = 3
def set_attempts(self, number):
self.__attempts = number
def get_attempts(self):
return self.__attempts
player = Player()
player.set_attempts(5)
print(player.get_attempts())💡 Methods are called with dot notation: Player.SetAttempts(5). A private attribute can only be reached through public methods.
Constructors and inheritance — the guide's Pet/Cat example (§10.2)
9618 only Run Run Python VB.NET · JavaCAIE pseudocodeCLASS PetPRIVATE Name : STRINGPUBLIC PROCEDURE NEW(GivenName : STRING)Name ← GivenNameENDPROCEDUREPUBLIC FUNCTION GetName() RETURNS STRINGRETURN NameENDFUNCTIONENDCLASSCLASS Cat INHERITS PetPRIVATE Breed : STRINGPUBLIC PROCEDURE NEW(GivenName : STRING, GivenBreed : STRING)SUPER.NEW(GivenName)Breed ← GivenBreedENDPROCEDUREPUBLIC FUNCTION Describe() RETURNS STRINGRETURN GetName() & " is a " & BreedENDFUNCTIONENDCLASSDECLARE MyCat : CatMyCat ← NEW Cat("Kitty", "Shorthaired")OUTPUT MyCat.Describe()
Pythonclass Pet:
def __init__(self, given_name):
self.__name = given_name
def get_name(self):
return self.__name
class Cat(Pet):
def __init__(self, given_name, given_breed):
super().__init__(given_name)
self.__breed = given_breed
def describe(self):
return f"{self.get_name()} is a {self.__breed}"
my_cat = Cat("Kitty", "Shorthaired")
print(my_cat.describe())💡 Object creation: <object name> ← NEW <class name>(<param1>, <param2> …). 2026 guide typo: Breed was INTEGER; 2027–29 corrects it to STRING.
Beyond the guide: exception handling (A2 §20.3) 9618 syllabus §20.3
The official guide has no exception syntax because §20.3 is examined in Python, VB.NET or Java (Paper 4). When you plan in pseudocode, use TRY … EXCEPT … ENDTRY — it is the accepted form and the Playground runs it.
CAIE pseudocodeDECLARE Entry : STRINGDECLARE N : INTEGERINPUT EntryTRYN ← STR_TO_NUM(Entry)OUTPUT 100 / NEXCEPTOUTPUT "Error: ", ERRORMESSAGE()ENDTRYOUTPUT "Still running"
Pythontry:
n = int(entry)
print(100 / n)
except Exception as e:
print("Error:", e)
print("Still running")💡 The EXCEPT block runs only if a statement inside TRY raises a runtime error (division by zero, failed conversion, index out of range, file not open…). Validation prevents predictable bad input; exception handling deals with what still goes wrong. ERRORMESSAGE() is a Playground convenience for the caught message.
2210 (O Level) differences 2210 syllabus
O Level pseudocode follows the same style. Differences you must know for Paper 2:
CAIE pseudocodeOUTPUT LENGTH("Computer") // 8OUTPUT SUBSTRING("Computer", 1, 4) // "Comp" (start, length)OUTPUT UCASE("hello") // "HELLO" — whole strings in 2210OUTPUT LCASE("HELLO")OUTPUT ROUND(3.14159, 2) // 3.14OUTPUT RANDOM() < 1 // random REAL 0 ≤ x < 1OUTPUT 17 DIV 5, " ", 17 MOD 5 // 3 2
Pythonlen("Computer")
"Computer"[0:4]
"hello".upper()
round(3.14159, 2)
import random; random.random()
17 // 5, 17 % 5CAIE pseudocodeDECLARE Total, Count, Num : INTEGERTotal ← 0Count ← 0INPUT NumWHILE Num <> -1 DOTotal ← Total + NumCount ← Count + 1INPUT NumENDWHILEOUTPUT "Total ", Total, " Count ", Count
Pythontotal = count = 0
num = int(input())
while num != -1:
total += num
count += 1
num = int(input())💡 Sentinel loops: INPUT before the loop and again at the end of the body.
CAIE pseudocodeDECLARE Line : STRINGOPENFILE "data.txt" FOR WRITEWRITEFILE "data.txt", "Zak"CLOSEFILE "data.txt"OPENFILE "data.txt" FOR READREADFILE "data.txt", LineCLOSEFILE "data.txt"OUTPUT Line
Pythonwith open("data.txt", "w") as f: f.write("Zak\n")
with open("data.txt") as f: line = f.readline().rstrip()