When designing larger pieces software it becomes impractical to have everything in one large program. So programs are structured into a main program/routine that contains many sub-routines that in turn are broken into more sub-routines. This improves the readability, maintainability and reusability of code.
This is also a useful design principle called Top Down Design. Break a large problem into a sequence of smaller problems that are in turn broken into smaller problems. Then the solution to the large problem is built back up from the solutions to all of the smaller problems. This aides in the generation of a solution and allows different parts of the solution to be assigned to different team members.
We're going to break up the process of drawing a child's version of a house shown on the right.
One procedure might be: First we draw the front wall, then the roof and the chimney. Then the door, including the handle and little window. Then the two big windows.
This can be documented in a structure chart which shows how procedures are called (run/executed). Each rectangle is a procedure and a line is a call to that procedure. Diagrams are read from the top-down and left-right.
Subroutines are also called Procedures, Functions, and Methods. In this course we won't usually distinguish between the different terms.
Submodules/Functions can be:
print(":P"), int(5.2), str(5.2), "guido".title()
are all part of the language definition in Pythonimport math; math.sin(0), math.sqrt(2)
are part of the math module in the standard librarypip
.Python is known for the number of easily available useful libraries; both in the standard library and PyPI. This is what makes it such a major force in web technology, science research, data science & machine learning, security, systems admin, etc... (python.org/about/apps)
You can define multiple procedures using the START procName ... END procName
blocks. These procedures are then called the usual way.
So, the basic structure is
START Main
Proc1()
FOR count ← 1 TO 3
Proc2(count)
NEXT count
END Main
START Proc1()
OUTPUT "In procedure 1"
END Proc1
START Proc2(num)
OUTPUT "In procedure 2"
OUTPUT num, "->", num*num
END Proc2
Things to note: Proc1
does not take any arguments (inputs) but it still needs the parentheses. Proc2
takes one argument which is called num
in the procedure (the parameter name) but passed the value of count
(the argument).
As a flow chart and structure chart it looks like
Here's a program for solving linear equations that separates the logic of the mathematics from logic of the user interface:
START Main
REPEAT
OUTPUT "Let's solve m*x + c = 0"
INPUT m, c
SolveLinear(m, c)
INPUT again
UNTIL NOT again
END Main
START SolveLinear(gradient, intercept)
IF gradient <> 0 THEN
OUTPUT "x = ", -intercept/gradient
ELSE
OUTPUT "No solutions for x"
END IF
END SolveLinear
In (simple) Python programs you need to define a function before you can use it. Here's the same linear solver we had in pseudocode
def solve_linear(gradient, intercept):
if gradient != 0:
print("x = ", -intercept/gradient)
else:
print("No solutions for x")
# Main Program
while True:
print("Let's solve m*x + c = 0")
m = float(input("m = ? "))
c = float(input("c = ? "))
solve_linear(m, c)
again = input("Again (y/n)? ")
if again[0].lower() != 'y':
break
Functions are often like those in mathematics - they take an input value and return an output value back to the program that called them. For example the built-in functions in Python:
int(...)
usually takes a string or float as an input and returns an integer value or error:x = int('3')
math.sqrt(...)
takes an int or float as input and returns a float or error:y = math.sqrt(x**2 + 4)
None
)You can make your own function that returns a value using the RETURN
or return
keywords in pseudocode or Python respectively.
Simple Example:
START Cube(number)
result ← number*number*number
RETURN result
END Cube
def cube(number):
result = number*number*number
return result
Example: Here is an algorithm to shuffle text by swapping each pair of adjacent letters
START shuffle(text)
out ← ""
FOR idx ← 1 TO length(text) STEP 2
IF idx = length(text)
out ← out + text[idx]
ELSE
out ← out + text[idx+1] + text[idx]
END IF
NEXT idx
RETURN out
END shuffle
Python version with testing, note the effects of indexing from 0 instead of 1:
def shuffle(text):
out = ""
for idx in range(0, len(text), 2):
if idx == len(text) - 1:
out = out + text[idx]
else:
out = out+text[idx+1]+text[idx]
return out
# Test
inputs = ["abcd", "abc", "testing",""]
outputs = ["badc", "bac", "ettsnig",""]
for idx in range(len(inputs)):
print("'{}' -> '{}': {}".format(
inputs[idx], outputs[idx],
shuffle(inputs[idx])==outputs[idx])
)
A car reversing sensor needs to measure the distance (using ultrasound), convert it into a frequency, and play an alarm for the driver.
Draw a structure chart for a program that will implement this.
Write a function in pseudocode, flowchart and Python that will determine if a given integer is a perfect power of 2.
You will probably need to use a while loop and some integer division.Starter code given below:
START powerOf2(num)
...
RETURN true // or false
END powerOf2
def power_of_2(num):
...
return True # or false
test_inputs = [1, 2, 4, 8, 1024, 3, 60, 0, -5, "a"]
test_outputs = [....]
# Loop over test inputs!
Snap is a popular card game in which players deal cards and react quickly to spot pairs of cards of the same rank. Cards are either dealt into separate piles around the table, one per player. The pack of cards is dealt out among the players in face-down stacks as equally as possible.
Play proceeds with the players taking it in turns to remove a card from the top of their stack and place it face-up on a pile in front of them. If two cards on the tops of any of these piles are ever identical (or, if a conventional pack of cards is used, are of the same number), the first player to shout "Snap!" takes both face-up piles and adds them to the bottom of their own stack. The player who accumulates all the cards wins.
Description from WikipediaDraw a structure chart for this game.