Innovate | Connect | Transform
ContactService statusUSD $

GICT knowledge base

Pseudocode to Python: Four Worked Examples with Tested Results

Published

Python

Pseudocode describes an algorithm before you commit to a programming language’s syntax. It is useful for agreeing on inputs, decisions, repeated work and failure cases. A plan can still contain mistakes, so trace it with sample inputs and test the Python implementation separately.

There is no single notation used everywhere. A course, exam or team may prescribe particular keywords and conventions. This article uses its own plain-English notation: SET assigns a value, RETURN ends a function, and a range described as 1 THROUGH n includes both endpoints. The blocks labeled Pseudocode are explanations, not executable Python or an exam-board template. Where an integer is required, these examples accept plain built-in int values, not Boolean values or subclasses.

Define the contract before the steps

Write down what input is accepted, what result is returned, what counts as invalid input and whether the algorithm changes any external state. For a file-management task, for example, a plan should distinguish listing proposed changes from actually moving files. For the small functions below, all work is in memory.

Planning notation Python equivalent
SET total TO 0 total = 0
IF a condition holds if condition: with an indented body
FOR EACH value IN values for value in values:
WHILE a condition holds while condition:
RETURN result return result inside a function

Do not turn a vague phrase such as “validate input” into a missing step. Specify what validation means for this problem. Likewise, “repeat until finished” needs a condition that can actually become false or an explicit exit.

Example 1: Distinguish positive, negative and zero

Contract: Accept an integer, excluding Boolean values, and return one of three labels. An else after “greater than zero” alone would group zero with negative numbers, so this plan needs a separate zero case.

Pseudocode, not executable:

IF value is not an integer, or is a Boolean
    REPORT a type error
IF value is greater than 0
    RETURN "positive"
ELSE IF value is less than 0
    RETURN "negative"
ELSE
    RETURN "zero"

Python:

def sign_label(value):
    if type(value) is not int:
        raise TypeError("value must be an integer")
    if value > 0:
        return "positive"
    elif value < 0:
        return "negative"
    else:
        return "zero"

assert sign_label(7) == "positive"
assert sign_label(-7) == "negative"
assert sign_label(0) == "zero"
print([sign_label(value) for value in [-1, 0, 1]])

Example 2: Accumulate a total, including an empty input

Contract: Accept an iterable of integers, excluding Boolean values, without replacing its stored items. An iterator is consumed as the function traverses it. Return zero when there are no values. Use total as the accumulator name so it does not hide Python’s built-in sum().

Pseudocode, not executable:

SET total TO 0
FOR EACH value IN values
    IF value is not an integer, or is a Boolean
        REPORT a type error
    ADD value TO total
RETURN total

Python:

def integer_total(values):
    total = 0
    for value in values:
        if type(value) is not int:
            raise TypeError("Every value must be an integer")
        total += value
    return total

values = [3, -1, 5]
assert integer_total(values) == 7
assert integer_total([]) == 0
assert values == [3, -1, 5]
print(integer_total(values))

A trace table makes each update visible:

Step Value Total afterward
Initialize None yet 0
First item 3 3
Second item -1 2
Third item 5 7

For an empty input the loop body never runs, and the initialized zero is returned. Once the input contract is handled, sum(values) is usually the simpler implementation; the loop here makes the translation process explicit.

Example 3: Translate an inclusive factorial loop

Contract: Accept an integer from 0 through 100 for this teaching example. The upper bound keeps the exercise’s work small; it is not a mathematical limit of factorial or a Python integer limit. Return 1 for zero and reject negative values rather than accidentally returning 1 for them.

Pseudocode, not executable:

REQUIRE n to be an integer, not a Boolean
REQUIRE 0 <= n <= 100
SET result TO 1
FOR factor FROM 1 THROUGH n, inclusive
    MULTIPLY result BY factor
RETURN result

Python:

def small_factorial(n):
    if type(n) is not int:
        raise TypeError("n must be an integer")
    if not 0 <= n <= 100:
        raise ValueError("This example accepts n from 0 through 100")
    result = 1
    for factor in range(1, n + 1):
        result *= factor
    return result

assert small_factorial(0) == 1
assert small_factorial(1) == 1
assert small_factorial(5) == 120
print(small_factorial(5))

Python excludes the stop value of range(), so the translation uses n + 1. When n is zero, range(1, 1) is empty and the initialized result remains 1. Checking those two facts is more useful than assuming the code is correct because it resembles the plan.

Example 4: Search and state the no-match result

Contract: Return the zero-based position of the first equal item, or None if no item matches. A result of zero means a match at the beginning, so do not test the result with a truthiness check when deciding whether a match exists.

Pseudocode, not executable:

SET position TO 0
WHILE position is less than the number of items
    IF items[position] equals target
        RETURN position
    ADD 1 TO position
RETURN no-match

Python:

def find_first(items, target):
    position = 0
    while position < len(items):
        if items[position] == target:
            return position
        position += 1
    return None

assert find_first(["web", "mail", "web"], "web") == 0
assert find_first(["web", "mail"], "mail") == 1
assert find_first(["web"], "dns") is None
assert find_first([], "dns") is None
print(find_first(["web", "mail"], "mail"))

This implementation expects an indexable, sized sequence; it is not a search function for every possible iterable. The increment is essential to termination when the current item does not match.

Practice and review

Extend the same process to an even/odd test: decide whether only integers are accepted, use remainder by 2, and test a negative integer as well as zero. For any algorithm, review empty input, first and last positions, equality boundaries, invalid types and the exact point at which a loop exits.

A flowchart can help communicate branching, but no generator or diagram proves the implementation correct. Keep a small test table beside the plan and rerun those cases after changing the Python code.

Verification: The four Python examples were executed independently on Python 3.12.14. Additional checks cover rejected types, negative/out-of-range factorial input, all factorial results from 0 through 100 against math.factorial(), empty inputs and first-match behavior. The pseudocode blocks were manually compared with their implementations, not claimed to run in Python.

References: Python control flow. For an example of a prescribed educational notation, see Cambridge’s Computer Science resources and pseudocode guides; follow the guide for the applicable examination year, not this article’s informal notation. Related: range boundaries.

Related guides

Account services are unavailable until the production backend is configured.