0% found this document useful (0 votes)
3 views20 pages

Year 7 Subroutine Note

The document explains the concept of subroutines in programming, specifically focusing on functions and procedures. It details how subroutines can simplify code by allowing reusable blocks of code that can be called multiple times, thus reducing redundancy and errors. Additionally, it covers the characteristics of functions, parameters, arguments, and various ways to define and call functions in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views20 pages

Year 7 Subroutine Note

The document explains the concept of subroutines in programming, specifically focusing on functions and procedures. It details how subroutines can simplify code by allowing reusable blocks of code that can be called multiple times, thus reducing redundancy and errors. Additionally, it covers the characteristics of functions, parameters, arguments, and various ways to define and call functions in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Subroutines

Functions
&
Procedur
es
Subroutines
Introduction
• Imagine you are writing a program that has 100 users who want to be able to change their name.
Imagine that to do this you had to write your code like this:
• If user1 wants to change their name: <code that asks for user1's new name and then edits it>
• Doing this 100 times till you gets to the hundredth person
• Your program would be very long and the chances of making a mistake would be high. Finding errors
would also be very tedious.
• To avoid these, we can write one smaller program, within our larger program, that can be called
whenever any user needs to have their name changed.
• These smaller program within our larger program is what we called subroutines.
• A subroutine is a code that performs a specific task, that can be called from anywhere of your
program.
Subroutines
Characteristics of subroutine
All subroutines in Python require:
• A keyword define written as (def)
• An identifier (a name)
Adding new functions
• A function definition(def) specifies the name of a new function, the purpose of a function and the
sequence of statements that execute when the function is called.
• def is a keyword that indicates that this is a function definition.
• A subroutine can then be called in the rest of the program as often as is required by its identifier.
Types of Subroutines
There are Two main types of subroutine:
• Functions
• procedures
Subroutines- Functions

• A Function: is a named sequence of statements that performs some useful operation.


• A function is a block of code which only runs when it is called.
• Functions may or may not take arguments and may or may not produce a result.
Creating a Function
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night, and I work all day.’)

• def is a keyword that indicates that this is a function definition.


• The name of the function is print_lyrics
• The rules for variable names are the same as for function names
• The empty parentheses( ) after the name indicate that this function doesn’t take any arguments.
• The first line of the function definition is called the header; and the rest is called the body.
• The header ends with a colon and the body has to be indented.
Subroutines- Functions

• The value of print_lyrics is a function object, which has type “function”.

Calling a function
• To call a function, use the function name followed by parenthesis:
• The syntax for calling the new function is print_lyrics()

Note:
• If you type a function definition in interactive mode, the interpreter prints ellipses (. . . ) to let you know
that the definition isn’t complete:
• To end the function, you have to enter an empty line (this is not necessary in a script).

• Once you have defined a function, you can use it inside another function. For example, to repeat the
previous refrain, we could write a function called repeat_lyrics:
Subroutines- Functions

def repeat_lyrics():
print_lyrics() def print_lyrics():
print_lyrics() print("I'm a lumberjack, and I'm okay.")

And then call repeat_lyrics: print('I sleep all night and I work all day.’)
>>> repeat_lyrics() #print_lyrics()

Pulling together the code fragments from the def repeat_lyrics():


previous section, the whole program print_lyrics()
looks like this:
print_lyrics()
#repeat_lyrics()
Subroutines- Functions

Flow Of Execution
• This program contains two function definitions: print_lyrics and repeat_lyrics.
• Function definitions get executed just like other statements, but the effect is to create function
objects.
• The statements inside the function do not get executed until the function is called, and the
function definition generates no output.
• In order to ensure that a function is defined before it is first use, you must know the order in which
the statements are been executed. This order is called the flow of execution.
• Flow of execution is the order in which statements are executed during a program run.
• Execution always begins at the first statement of the program. Statements are executed one at a
time, in order from top to bottom.
Subroutines- Functions

Parameters and arguments


• Inside the function, the arguments are assigned to variables called parameters.
• Parameter is a name used inside a function to refer to the value passed as an argument.
• Argument is a value provided to a function when the function is called.
• Note: at times the term parameter and argument are used interchangeable to mean the same thing:
i.e., information that are passed into a function.
Example of a function that takes an argument
def print_twice(bruce):
print(bruce)
print(bruce)
• This function assigns the argument to a parameter named bruce. When the function is called, it
prints the value of the parameter (whatever it is) twice.
• This function works with any value that can be printed.
Subroutines- Functions
#This function works with any value that can be You can also use a variable as an argument:
printed
michael = 'Erica, is two of Empress.'
def print_twice(bruce): print_twice(michael)
print(bruce)
print(bruce) Note:
print_twice('bruce') • The name of the variable we pass as an
argument (michael) has nothing to do with the
#print_twice('spam’) name of the parameter (bruce).
#print_twice('spam'*4) • It doesn’t matter whatever value is called back
#print_twice('egg’) home (in the caller); here in the print_twice, we
call everybody bruce.
• It is common to say that a function “takes” an
brue in def: is the parameters argument and “returns” a result. The result is
brue or spam in print() is the arguments passed called the return value.
to the
Subroutines- Functions
• To return a result from a function, we use the return statement in our function.
• For example, we could make a very simple function called addtwo that adds two numbers together and
returns a result.
def addtwo(a, b):
added = a + b
return added
x = addtwo(3, 5)
print(x)
Explanation/ interpretation
1. When this script is run, the print statement will print out “8” why?
2. The addtwo function was called with 3 and 5 as arguments. Within the function, the parameters a and b
were 3 and 5 respectively.
3. The function computed the sum of the two numbers and placed it in the local function variable named
added.
4. it used the return statement to send the computed value back to the calling code as the function result,
Subroutines
Types of subroutines Procedure pseudocode example
• Procedures are small sections of code that
can be reused.
• They are just the same as functions, but they
do not return a value to the main program.
• In pseudocode, a procedure is named and
takes the form:
PROCEDURE ... ENDPROCEDURE

• They are called by using the CALL statement.


• The CALL statement is used to execute the
procedure.
• However, any values required by the procedure
must be passed to it at the same time:
Subroutines- Functions
Advantages of subroutines
• It gives you an opportunity to name a group of statements, which makes your program easier to
read, understand, and debug.
• it make a program smaller by eliminating repetitive code. Later, if you make a change, you only have
to make it in one place.
• Dividing a long program into subroutine allows you to debug the parts one at a time and then
assemble them into a working whole.
• Once you write and debug one, you can reuse it.
Subroutines- Functions

Example of Function with one argument (fname).


def my_function(fname):
print(fname + " fruit")
my_function(“Mango")
my_function(“Orange")
my_function(“Pawpaw")

When the function is called, we pass along a first name, which is used inside the function to print the full
name:
Subroutines- Functions

For Example, this function expects 2 arguments, and gets 2 arguments:


def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
Note: If you try to call the function with 1 or 3 arguments, you will get an error:

This function expects 2 arguments, but gets only 1, error is displayed:


def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil")
Subroutines- Functions

Arbitrary/random Arguments, *args


• If you do not know how many arguments that will be passed into your function, add a * before the
parameter name in the function definition. This way the function will receive a tuple of arguments, and
can access the items accordingly:
Example
• If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")

Keyword Arguments
You can also send arguments with the key = value syntax. This way the order of the arguments does
not matter.
Subroutines- Functions

Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

Arbitrary Keyword Arguments, **kwargs


• If you do not know how many keyword arguments that will be passed into your function, add two
asterisk: ** before the parameter name in the function definition. This way the function will receive a
dictionary of arguments, and can access the items accordingly:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
Subroutines- Functions

Default Parameter Value Passing a List as an Argument


• The following example shows how to use a • You can send any data types of argument to
default parameter value. If we call the function a function (string, number, list, dictionary
without argument, it uses the default value: etc.), and it will be treated as the same data
type inside the function.
• For example, if you send a List as an
Example
argument, it will still be a List when it reaches
def my_function(country = "Norway"): the function:
print("I am from " + country)
my_function("Sweden") Example
my_function("India") def my_function(food):
my_function() for x in food:
my_function("Brazil") print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Subroutines- Functions

Return Values Example


• To let a function return a value, use the return def myfunction():
statement: pass
Example Positional-Only Arguments
def my_function(x): • You can specify that a function can have
return 5 * x ONLY positional arguments, or ONLY
print(my_function(3)) keyword arguments.
• To specify that a function can have only
print(my_function(5))
positional arguments, add , / after the
print(my_function(9)) arguments:
The pass Statement Example
• function definitions cannot be empty, but if for def my_function(x, /):
some reason you have a function definition
with no content, put in the pass statement to print(x)
avoid getting an error. my_function(3)
Subroutines- Functions

Without the , / you are actually allowed to use Keyword-Only Arguments


keyword arguments even if the function expects • To specify that a function can have only keyword
positional arguments: arguments, add *, before the arguments:
Example Example
def my_function(x): def my_function(*, x):
print(x) print(x)
my_function(x = 3) my_function(x = 3)
But when adding the , / you will get an error if • Without the *, you are allowed to use positionale
you try to send a keyword argument: arguments even if the function expects keyword
Example arguments:
def my_function(x, /): Example
print(x) def my_function(x):
my_function(x = 3) print(x)
my_function(3)
Subroutines

QUESTION TIME?

You might also like