Procedures

[/vc_row_inner]

So far you have only written linear code – instructions that run from top to bottom in order.

For example:

print("Hello")
print("How are you?")
print("Goodbye")

This works for small programs, but bigger programs can get messy. To make programs easier to organise, we can use subprograms.

Sub-programs

A subprogram is a separate set of instructions that has its own name.

  • You write it once.
  • You can use it (or call it) as many times as you like.
  • This avoids repetition and makes code clearer.

Procedures

A procedure is one type of subprogram.

  • It has a name.
  • It contains a set of instructions.
  • You can pass in values using parameters.
def greeting():
    print("Hello")
    print("Welcome to the program!")
    print("Enjoy your day!")

# main program
greeting()
greeting()
Hello
Welcome to the program!
Enjoy your day!
Hello
Welcome to the program!
Enjoy your day!
PROCEDURE greeting()
    OUTPUT "Hello"
    OUTPUT "Welcome to the program!"
    OUTPUT "Enjoy your day!"
END PROCEDURE

# main program
CALL greeting()
CALL greeting()

Explanation

  • Line 1 – def greeting(): tells Python to create a subprogram called greeting.
  • Lines 2–4 – These instructions are stored as part of the procedure. They will only run when the procedure is called.
  • Line 7 – greeting() is a procedure call. Python looks up the saved procedure and now runs the instructions inside it (lines 2–4).
  • Line 8 – The procedure is called again, so the same instructions are run a second time.

Key idea

  • Defining a procedure saves it in memory with a name.
  • Calling the procedure later is what actually makes the instructions run.