3.2.10 - Structured programming and subroutines (procedures and functions) Flashcards
(8 cards)
Subroutines
A named block of code that performs a specific task and can be reused throughout a program.
Advantages of subroutines
Reduces repetition
Makes code easier to read, test, and maintain
Allows reuse in other programs
Parameters
A variable passed into a subroutine. It allows data to be passed from the main program to the subroutine.
def greet(name) - name is the parameter
Procedure
A procedure is a subroutine that performs a task but does not return a value.
python:
def greet(name):
print(“Hello”, name)
pseudocode:
PROCEDURE greet(name)
OUTPUT “Hello “ + name
ENDPROCEDURE
Function
A subroutine that performs a task and returns a value to where it was called.
python:
def square(num):
return num * num
pseudocde:
FUNCTION square(num)
RETURN num * num
ENDFUNCTION
Local variable
A variable declared inside a subroutine.
It can only be used within that subroutine.
def example():
x = 5 # local to this function
Global variable
A variable declared outside any subroutine and accessible from anywhere in the program.
x = 5
def show():
print(x) # accesses global x
Why should you use local variables instead of global ones?
Prevent accidental changes
Keeps subroutines self-contained
Improves readability and reduces bugs