Procedures and functionsWriting a procedure

When writing programs, we should avoid long, repetitive code. Procedures and functions help to keep our programs simple and short.

Part ofComputer ScienceProgramming

Writing a procedure

Writing a is extremely simple. Every procedure needs:

  • a name
  • the code to perform the task

Writing a procedure in Python

Consider this excerpt from a game program which prints player information on the screen:

print("Your score: " + str(score))
time.sleep(1)
print("High score: " + str(high_score))
time.sleep(1)
print("Lives remaining: " + str(lives))
time.sleep(1)

To create a procedure, first give the procedure a name. A good name for the player information procedure could be ‘update_display’. Python uses the def to name a procedure. Note the brackets at the end of the procedure’s name:

def update_display():

The procedure is then written indented beneath the def statement:

def update_display(): print("Your score: " + str(score)) time.sleep(1) print("High score: " + str(high_score)) time.sleep(1) print("Lives remaining: " + str(lives)) time.sleep(1)