0% found this document useful (0 votes)
2 views

Revision Notes -11 Functions

The document provides an overview of functions and procedures in Python, explaining their definitions, differences, and advantages. It details how to define and call functions, including examples for calculating areas and performing arithmetic operations, while also discussing local and global variables. The content emphasizes the importance of using functions and procedures to improve code readability, reduce redundancy, and streamline programming tasks.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Revision Notes -11 Functions

The document provides an overview of functions and procedures in Python, explaining their definitions, differences, and advantages. It details how to define and call functions, including examples for calculating areas and performing arithmetic operations, while also discussing local and global variables. The content emphasizes the importance of using functions and procedures to improve code readability, reduce redundancy, and streamline programming tasks.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Teach Computer

Science
GCSE Python

Functions

teachcomputerscience.co
m
1
.
Revision notes

teachcomputerscience.co
m
Introduction
In the first topic of this course, “Introduction to Python”, we
learnt about simple procedures. Procedures allow us to group a
block of code under a name. This block of code can be called
anywhere in the program to execute the instructions in it. In
Python, the def keyword denotes the start of a procedure or
function definition. Defining a simple procedure named Hello,
#procedure Hello
def Hello():
print("Hello!, Welcome to Trinket")
When called, this procedure displays the text stated.

When this program is executed, the output is,

Why do we need procedures? Programs implement several


tasks. Many times, similar tasks are repeated. Typing the same
code multiple times is time-consuming. Such tasks are written
as modules such as functions and procedures. Functions are
similar to procedures; the only difference is that a function
returns a value, but a procedure does not return a value. These
modules can be called multiple times in the main program
reducing the time taken.
teachcomputerscience.co
m
The advantages of using functions and procedures are:
• The overall size of the code is reduced as the codes are not
repeated several times.
• The use of functions and procedures improves the
readability of the program as only the names of these
modules are used in the main program.
• Reduces the time taken to write and test the program.
Repeated codes can be called from the main program and
it’s enough if they are tested once.
• Reduces the time taken to debug the program. The code of
functions and procedures are checked only once.
• Programming languages also provide in-built, pre-written
and thoroughly checked functions that can be used by
programmers. This saves time and reduces the possibility of
errors. For example: the len() function is used to find the
number of characters in a string and the number of
elements in an array.

Function
Functions are subprograms that can be called whenever
required from the main program. The inputs for the function are
passed from the main program. Once the function code is
executed, the results are returned to the function call
statement of the main program. The use of a function reduces
the time taken and improves the readability of the program.
The user need not know the function code. It’s enough if the
user knows how to use the function, that is, what inputs are
given, what outputs are produced. This is an application of
abstraction.
The step-by-step process of a function call is:
i. The main program executes until it reaches a function call
statement.
ii. The function call statement transfers the control to the
function. The inputs are also passed using this statement.
teachcomputerscience.co
m
i. The function code is executed. In other words, the input
passed to the function is processed.
ii. The control is transferred back to the main program once
the execution of the function is complete or a statement
passes the control out of the function.
iii. The results calculated by the function are returned to the
main program. This happens at the function call
statement. Thereafter, the main program continues the
execution of the program.

Execution of Function
main program definition

Execution of
Function call
function code

Continued Calculated
execution of results by
main program function

Figure 1: Function
call

The definition of a function requires:


• Name of function
• Inputs to be passed to the function
• Function code
• Outputs that are produced by the function

teachcomputerscience.co
m
Functions: Example
program
Let us understand more about functions using an example. Let
us use a function to calculate the area of a circle.
#function definition
def areaCircle(radius):
area = 3.142*radius*radius
return area
Calling this function,
#main program to call function areaCircle
r=int(input(“Enter radius of circle:”)
A=areaCircle(r)
print(“The area of circle is: %.2f” %A)
Executing the above program, the result obtained is given.

In the above function:


• Name of function: areaCircle
• Input passed to function: radius
• Function code: area=3.142 × radius × radius
• Output from the function: area
The area of circle calculation is used in several mathematical
calculations, such as finding the volume of a cylinder, finding
the volume of a cone and many more.

teachcomputerscience.co
m
teachcomputerscience.co
m
Returning several values
from a function
A function may return several values. In such cases, the
different values are separated by a comma. A function that
takes in two input values, performs the four basic arithmetic
operations and returns the results is given.
#function definition
def basicArithmetic(a,b):
sum1=a+b
diff=a-b
product=a*b
quotient=a/b
return sum1, diff, product, quotient
#main program
num1=int(input('Enter number1: ‘))
num2=int(input('Enter number2: ‘))
p, q, r, s=basicArithmetic(num1,num2)
print("Sum =", p)
print("Difference =",q)
print("Product =",r)
print("Quotient =", s)

The four values calculated by the function are returned using a


single statement. The function call statement also has four
different variables to get the values calculated by a function.
An output of this program is given alongside.

teachcomputerscience.co
m
Procedures
Similar to functions, procedures are subprograms defined
outside the main program. The difference between procedures
and functions is procedures do not return a value, but functions
return a value.
An example of a Python program that uses a procedure to print
text entered by the user several times is given below.
#Procedure definition
def printProcedure(text, num):
for i in range(0,num):
print(text)

#main program to print text


string=str(input('Enter the text: '))
times=int(input('Enter the number of times to print text: '))
printProcedure(string,times)
print('Execution of procedure is complete')
The procedure ‘printProcedure’ is defined and is called from the
main program. It can be noted that the procedure does not
return any value. Here it prints the text multiple times. Once,
the execution of the procedure is complete, the control is
passed to the main program. The output of the above program
is:

teachcomputerscience.co
m
Global and local variables
Variables and constants declared inside a function or procedure
are local to that subroutine. Consider the example program
given below that shows how a variable of the same name in a
function and main program behaves.
#procedure definition
def procA():
myString=“procedure A"
print("Executing statements in", myString)
def procB():
myString="procedure B"
print("Executing statements in", myString)
#main program
myString="main program“
print("Executing statements in", myString)
procA()
print("Executing statements in", myString)
procB()
print("Executing statements in", myString)
Executing this program, the output is,

It can be noted that the value of myString in a subroutine is


only local to that subroutine. Outside the procedure, myString
is assigned the value in the main program.
teachcomputerscience.co
m
To enable the usage of a variable defined in a subroutine
throughout the program, it has to be made global using the
keyword global. An example showing the use of local and
global variables in Python is given below.
x=2
#procedure definition
def procC():
#global variable
global x
y=5
x=x*5
print(x)
print(y)
#main program
print("Calling the procedure...")
procC()
In this program, x is a global variable and y is local to procC().
The value of x can be accessed in the main program also, but
the value of y is undefined outside the subroutine. Trying to
print the values of x and y outside the function results in
NameError for variable y.
#procedure definition
def procC():
global x
y=5
x=x*5
print(x)
print(y)
#main program
print("Calling the procedure...")
procC()
print("Values of x =",x)
print("Values of y =",y)

teachcomputerscience.co
m

You might also like