gl/ripetizioni

From flowchart to Python code

Flowchart blocks, selection and iteration, pseudocode and translation into Python, types and casting: three worked examples from diagram to code.

by Gaetano Livornese

Read the original in Italian

It is early October and in Year 2 of Italian high school, in classes with computing (at the science liceo applied-sciences option it is 2 hours a week, but the same topic also appears in other tracks), algorithms are getting under way: spreadsheet, flowcharts and then the first programming language. The test, written or practical, arrives in five to eight weeks. The point where students get stuck is not the diagram itself, but the next step: from the diagram to the code, with the data types and casting that go with it. This post is for getting there already trained.

If the spreadsheet is the other half of the programme, I talk about it in spreadsheets and algorithms in Year 2. Here I stay on the path flowchart, pseudocode, Python.

What an algorithm is, in practice

An algorithm is a finite sequence of unambiguous steps that turns input data into a result. The flowchart draws it; the pseudocode writes it in structured plain language; the code writes it in a language the computer executes. They are three ways of writing the same reasoning, and the skill required is moving from one to another without losing pieces.

The blocks of the diagram

Each shape has a precise meaning and the test often asks for it:

ShapeMeaningExample
OvalStart / EndSTART, END
ParallelogramInput / Outputread a, write result
RectangleProcess (calculation, assignment)sum = sum + i
DiamondDecision (two exits: Yes / No)a > b ?

Arrows show the order. A diamond always has two exits, a rectangle only one. Three structures are enough for almost everything:

  • sequence: blocks one after another;
  • selection: a diamond and two branches (if… then… else);
  • iteration: a diamond from which an arrow goes back, forming a loop.

From diagram to code: the procedure

  1. Draw the diagram, or write the steps in a numbered list.
  2. Rewrite it in pseudocode, one line per block.
  3. Translate line by line into Python: each input parallelogram becomes input(), each output parallelogram print(), each rectangle an assignment, each diamond an if or a while.
  4. Try the code by hand with two or three values (the “trace table”) before running it.

A diagram in words can be written like this, with arrows in ASCII, and it is a format you can also use for revision.

Exercise 1: the maximum of two numbers

Diagram:

(START)
   |
   v
/ read a, b /
   |
   v
< a > b ? > --Yes--> [ max = a ] --+
   |                               |
   No                              |
   |                               |
   v                               |
[ max = b ] -----------------------+
                                   |
                                   v
                           / write max /
                                   |
                                   v
                                (END)

Pseudocode:

START
  read a, b
  IF a > b
    THEN max = a
    ELSE max = b
  write max
END

Python:

a = int(input("First number: "))
b = int(input("Second number: "))

if a > b:
    maximum = a
else:
    maximum = b

print("The maximum is", maximum)

Hand trace with a = 7, b = 12: the condition 7 > 12 is false, so the else branch runs, maximum is 12 and 12 is printed. With a = 9, b = 9 the condition is false and maximum is 9, which is correct: the two numbers are equal.

For Year 2 computing there is not yet a dedicated practice test on the site; to train your logical-mathematical reasoning meanwhile you can use the high school practice tests.

Exercise 2: the sum of the first n numbers with a loop

I want the sum given . You need an accumulating variable (total) and a counter (i) that runs from 1 to .

Diagram as a numbered list:

  1. START
  2. read n (parallelogram)
  3. total = 0, i = 1 (rectangle)
  4. diamond: i <= n ?
    • Yes → step 5
    • No → step 7
  5. total = total + i (rectangle)
  6. i = i + 1, then go back to step 4 (the backward arrow is the loop)
  7. write total (parallelogram)
  8. END

Pseudocode:

START
  read n
  total = 0
  i = 1
  WHILE i <= n
    total = total + i
    i = i + 1
  write total
END

Python:

n = int(input("Up to which number? "))

total = 0
i = 1
while i <= n:
    total = total + i
    i = i + 1

print("The sum is", total)

Trace table with :

stepitotal beforetotal after
1101
2213
3336
44610

Then i becomes 5, the condition 5 <= 4 is false and the loop ends: the program prints 10. As a check, Gauss’s formula gives

and it agrees. Two things not to forget: initialisation (if you don’t put total = 0 the program won’t start, because total doesn’t exist) and updating the counter (if you remove i = i + 1 the loop never ends).

Exercise 3: even or odd number

An integer is even if the remainder of the division by 2 is zero. In Python the remainder is obtained with the % operator.

Diagram as a numbered list:

  1. START
  2. read n
  3. diamond: is the remainder of n divided by 2 equal to 0 ?
    • Yes → write “even”
    • No → write “odd”
  4. END (the two branches rejoin here)

Pseudocode:

START
  read n
  IF remainder(n, 2) = 0
    THEN write "even"
    ELSE write "odd"
END

Python:

n = int(input("Enter an integer: "))

if n % 2 == 0:
    print(n, "is even")
else:
    print(n, "is odd")

Test: with n = 14, 14 % 2 is 0, so it prints “14 is even”. With n = 7, 7 % 2 is 1, so “7 is odd”. With n = 0 it prints “even”, and that is right: zero is even.

Data types and casting

This is where the first real mistake arises. The input() function always returns a string, even if the user types a number. This code looks right and isn’t:

a = input("First number: ")
b = input("Second number: ")
print(a + b)

With 3 and 4 it prints 34, not 7: the + between two strings concatenates them. To do calculations you need casting, that is, type conversion:

a = int(input("First number: "))
b = int(input("Second number: "))
print(a + b)

The types you meet at this stage are four:

TypeWhat it isExampleConversion
intinteger7int("7")
floatnumber with a decimal part3.5float("3.5")
strtext string"hello"str(7)
booltrue or falseTruebool(0) is False

Two details that cost you in a test. In Python the decimal separator is the point, not the comma (the Italian convention): float("3,5") raises an error. And the division / always returns a float: 7 / 2 gives 3.5, while 7 // 2 gives 3 (integer division) and 7 % 2 gives 1 (remainder). If you read a height or a price, use float(input(...)); if you read a count, int(input(...)).

Typical mistakes

  • Indentation. In Python indentation is not aesthetics: it defines which lines are inside the if or the while. If total = total + i falls out of the indentation, it is executed only once, after the loop. The code runs and gives a wrong result, which is the hardest mistake to see.
  • = instead of ==. A single = assigns, a double == compares. if n % 2 = 0: gives a syntax error; the right comparison is if n % 2 == 0:.
  • Forgetting the colon after if, else, while.
  • Forgetting the casting. Without int() the program doesn’t stop, but compares strings: "9" > "12" is true, because the comparison is alphabetical. The maximum between 9 and 12 would come out as 9.
  • Infinite loop: the counter update is missing, or the condition never becomes false.
  • Uninitialised variable: using total before writing total = 0.

A good method for the written test: after writing the code, run it by hand with a small value and write the trace table. The teacher often requires it, and in any case it is the quickest way to find out where the code doesn’t do what you thought.

How to train over the coming weeks

  1. For every exercise always do the three steps: diagram, pseudocode, Python. Skipping the pseudocode seems like a saving and is instead the step that puts your ideas in order.
  2. Rewrite the three exercises above without looking at them, then vary: the minimum of two numbers, the sum of the even numbers up to , the maximum of three numbers.
  3. For each program try at least one edge case: zero, equal numbers, a single element.
  4. When the code works, change one line on purpose and predict what happens. Understanding an error before seeing it is exactly what you need in a test.

For the next step of the programme, that is writing in Python with more independence, you will find Python programming from scratch. When functions arrive there is passing parameters by value and by reference, and later bubble, selection and insertion sort, which are nested loops written with the same method.

If in class you are already going faster, or if the move from diagram to code just doesn’t add up for you, we are glad to talk: the computer science page tells how I work, and from contact you can book a free introductory call to work out where it is best to start.

Keep reading

Want to put what you read into practice?

Let's talk for 30 minutes, free: we look together at where you are stuck and I tell you honestly how I can help.

Or message me on WhatsApp.