3.2.2, 3.2.10 - Subroutines, parameters and return values (Python)

3.2.2, 3.2.10 - Subroutines, parameters and return values (Python)

Subroutines give a named task its own code. You will define and call Python subroutines, pass more than one parameter and return a calculated result for the caller to use.

Defining and calling subroutines

A subroutine is a named block written separately from the main sequence and executed when the program calls it.

Subroutine

A named, out-of-line block of code that can be called by its name to perform a task.

Python defines a subroutine with def, a name, parentheses and a colon. Its body is indented.

Python
def show_heading():
    print("Club bookings")
    print("--------------")

show_heading()
print("Enter a booking")
show_heading()

Defining the body does not display the heading. The first call runs it, execution returns to the main sequence, the booking message runs, then the second call runs the same body again. A procedure performs an action without returning a useful result; a function returns a value. Python uses def for both roles.

One definition avoids duplicating a heading or calculation in many places. A correction can be made once, a descriptive name explains the main program, and the task can be tested separately. AQA supplied pseudocode uses SUBROUTINE and ENDSUBROUTINE; respond in native Python when the question requests Python.

Passing more than one parameter

Parameters pass the data needed for a subroutine's task into that subroutine.

Python
def show_result(player_name, score):
    print(player_name, "scored", score)

show_result("Mina", 12)
show_result("Omar", 9)

During the first call, player_name receives "Mina" and score receives 12. The second call supplies a different pair. For these positional calls, the values match the parameter names in order. Swapping them would make the output describe a number as a player and a name as a score.

AQA uses parameter for both the names in the definition and the values passed at a call; other sources may call the latter arguments. More than one parameter allows a reusable task to receive a complete combination of relevant data. Define the interface clearly: this subroutine expects a string name and a numeric score, and displays a result; it does not prompt for its own input.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account