6.4. Pseudocode#
Pseudocode comes in very handy for helping you to brainstorm and plan how to best approach the problem in Python, before you actually start writing the code, which saves time (especially for more complex problems). With pseudocode, we write down the logic and steps of our program in plain English before putting it into Python syntax (i.e., actual code). Note that Python already resembles plain English, so writing pseudocode isn’t a difficult task.
6.4.1. Why?#
Why would you bother and take extra time to write pseudocode?
Pseudocode helps you to figure out the logic of the problem. This way, you can more easily communicate and think about what you’re doing. You also avoid running into problems later, during programming.
Pseudocode saves time in the code planning phase. It’s easy and quick to write, so it’s more effective than delving directly into Pyhon syntax, especially for more complex problems.
Pseudocode allows you to talk about technical solutions with everyone, including people who don’t know how to program or aren’t familiar with the syntax of your favourite programming language. This is immensely helpful when working in teams (e.g., in your future job).
6.4.2. How?#
How do you approach writing the pseudocode? In essence, you write down each step in plain English, using keywords that describe what you would do in Python.
Let’s look at some examples.
6.4.2.1. Example 1: Output#
For outputs (print
statements), you can use words such as PRINT or DISPLAY in your pseudocode.
Python:
print("Nanobiology")
Pseudocode:
PRINT "Nanobiology"
6.4.2.2. Example 2: Input#
For input
, you can use words such as READ or GET in your pseudocode. Describe also how you prompt the user to give program the input.
Python:
number = input("Enter a number:")
Pseudocode:
PROMPT for number
GET number
6.4.2.3. Example 3: Calculation#
For calculations, you can use math terms that you’d normally use, such as DIVIDE, SUBTRACT, MULTIPLY, etc.
Python:
density = mass / volume
Pseudocode:
DIVIDE mass by volume
6.4.2.4. Example 4: Variables#
For assigning variables, you can use words such as SAVE, SET, or STORE.
Python:
pi = 3.14
Pseudocode:
SET pi to 3.14
6.4.2.5. Example 5: Conditional logic#
For conditional statements, your pseudocode can contain keywords very similar to Python, as the syntax already is like plain English (IF, ELSE).
Python:
if accurate == True:
accurate_measurements += 1
else:
print("Measurement is inaccurate.")
Pseudocode:
IF accurate is True THEN
ADD 1 to accurate_measurements
ELSE
DISPLAY "Measurement is inaccurate"
ENDIF
6.4.2.6. Example 6#
Let’s look at an example combining several elements discussed above.
Python:
ph_value = float(input("Enter pH value:"))
if ph_value >= 7:
print("Neutral or alkaline")
else:
print("Acidic")
Pseudocode:
PROMPT for ph_value
GET the ph_value and make it a number
IF ph_value is greater than or equal to 7 THEN
DISPLAY "Neutral or alkaline"
ELSE
DISPLAY "Acidic"
ENDIF