13. From Flowchart to Code: The Bridge

The one skill that ties it all together

A flowchart shows what should happen; code tells the computer how. Once you see that every flowchart shape maps to a small, predictable piece of Python, translation stops being mysterious. This chapter makes that mapping explicit and then walks a single problem all the way across the bridge.

Symbol / construct → Python mapping

Flowchart symbolPseudocode constructPython equivalent
Oval (terminator)START / END, RETURNdef name(...): … return
Rectangle (process)assignment / calculationa statement, e.g. total = total + i
Diamond (decision)IF / ELSE IF / ELSEif / elif / else:
Parallelogram (I/O)INPUT / OUTPUTinput() / print()
Arrow looping backWHILE / REPEAT / FORwhile condition: / for x in ...:
Connector into a boxsequence (next step)the next line of code (indentation)

Worked example: sum of even numbers from 1 to N

Problem

Read a number N, then add up every even number from 1 to N and print the total. For N = 6 the even numbers are 2, 4, 6, so the answer is 12.

Start input N total=0; i=1 i <= N? i even? total = total + i i = i + 1 output total End Yes Yes No No

Pseudocode

SUM_EVENS:
    N = INPUT
    total = 0
    i = 1
    WHILE i <= N:
        IF i is even:
            total = total + i
        i = i + 1
    OUTPUT total

Trace table

Tracing with N = 6:

ii <= 6?i even?total
1YesNo0
2YesYes2
3YesNo2
4YesYes6
5YesNo6
6YesYes12
7No → stop—12

In Python

Notice how each flowchart shape became one line, following the mapping table above:

def sum_evens(n):
    total = 0            # process box
    i = 1                # process box
    while i <= n:        # loop-back arrow
        if i % 2 == 0:   # decision diamond
            total += i   # process box
        i += 1           # process box
    return total         # terminator

N = 6                    # stands in for input()
print(sum_evens(N))

Output:

12

Practice challenges

Now try the whole bridge yourself. For each problem below, draw a flowchart, write pseudocode, build a trace table on a sample input, then code it in Python:

  1. Read a number and print whether it is odd or even.
  2. Read 5 numbers and print their average.
  3. Print the multiplication table (1 to 12) for a number the user chooses.
  4. Read a number N and print its factorial (N! = 1×2×…×N).
  5. Count how many vowels are in a word the user types.
  6. Decide whether a given year is a leap year.
  7. Read a list of marks and print how many are a pass (≥ 40) and how many fail.
  8. Check whether a short word is a palindrome (reads the same backwards).