12-procedures.py
python-for-j277 / subroutines  ·  Lesson 12
Lesson 12 — Subroutines

Subroutines: Procedures

Name a block of code so you can reuse it.

A subroutine is a named block of code you can run whenever you like. A procedure is a subroutine that does a job but does not send a value back.

Defining and calling a procedure

hello.py
def say_hello():
    print("Hello!")
    print("Welcome to the program.")

say_hello()
say_hello()
Output
Hello!
Welcome to the program.
Hello!
Welcome to the program.
How it works
  • def creates a subroutine and gives it a name.
  • The indented lines are the body — they do not run until the subroutine is called.
  • say_hello() calls it; we call it twice, so the body runs twice.

Passing information with parameters

welcome.py
def welcome(name):
    print("Hello", name)
    print("Good to see you")

welcome("Ava")
welcome("Ben")
Output
Hello Ava
Good to see you
Hello Ben
Good to see you
How it works
  • name inside the brackets is a parameter — a box that receives a value when the procedure is called.
  • welcome("Ava") sends "Ava" into name for that run.
  • The same procedure does its job with different data each time.

Several parameters

area.py
def show_area(width, height):
    area = width * height
    print("Area is", area)

show_area(4, 5)
show_area(3, 7)
Output
Area is 20
Area is 21
How it works
  • A procedure can take several parameters, separated by commas.
  • The values are matched to the parameters in order: 4 goes to width, 5 to height.
A procedure does a jobIt may take parameters, but it does not return a value.

What you have learned

  • A subroutine is a named, reusable block of code.
  • def defines it; name() calls it.
  • Parameters let you pass data in, matched in order.
  • A procedure does a job but sends nothing back.