Functions – User defined
Dr Nurbiha A Shukor
SEKOLAH PENDIDIKAN,
FAKULTI SAINS SOSIAL DAN KEMUANUSIAAN, UTM 2020
Introduction
As you already know, Python gives you many built-in
functions like print() , input() , float (), etc. but you can also
create your own functions.
These functions are called user-defined functions.
Example
print (‘Hi’)
def lyric ():
print(‘You are my fire’)
print (‘The one desire’)
print (‘Believe when I say’)
lyric ()
print(‘Done’)
Function-related statements and expressions
Statement or Examples
expressions
Call myfunc(‘basket’, meat=chicken, *rest)
expressions
def def printer(message):
print(‘Hello’ + message)
return def tambah(a, b=1, *c):
return a+b+c[0]
Defining a Function
Here are simple rules to define a function in Python:
Function blocks begin with the keyword def followed by the
function name and parentheses ( ).
Any input parameters or arguments should be placed within
these parentheses. You can also define parameters inside
these parentheses.
The code block within every function starts with a colon (:)
and is indented.
Defining a Function
Python keyword/reserved words cannot be used as function
name
Programmer or user can define function by using def function
name
Then follow by parameter in the parenthesis ()
Function can be defined with and without arguments or
parameter
Syntax:
def functionname(parameters/arguments):
function_statements
return [expression]
Defining a Function
def function_name():
statement (must be indented)
name of the function
def hello (): we define the function as hello
print ("Hello, World!") statement in the body of hello function
Calling a Function
Following is the example to call lyric() function:
name of the function
def lyric():
print (‘You are my fire’)
print (‘The one desire’)
Statements in function lyric()
print(‘How are you? Let us look at some lyrics’) 1 Will be executed first by Python
lyric() 2 Will be executed next, calling the function lyric()
Output
How are you? Let us look at some lyrics
You are my fire
The one desire
Function without argument/parameter
def function_name (): No parameter in parenthesis
def UTM_slogan ():
print("I am UTM")
print("I Love UTM")
print("UTM My Home")
UTM_slogan () # call the function
Function with argument/parameter
def function_name (parameter1@argument1,
parameter2@argument2):
def kira_purata (x, y): #define function
average = (x+y)/2
print(‘Average is:’, average) #pass the parameter
kira_purata (100, 12) #call the function
Output:
Purata 100 dan 12 adalah 56
Using ‘Return’
Often a function will take its’ arguments, do some
computation, and return the value of the function call in the
calling expressions.
The ‘Return’ keyword is used for this purpose
Return statement is used to ends the function execution and
’sends back’ the result of the function.
Return Statements
The statement return [expression] exits a function, optionally
passing back an expression/values to the caller.
A return statement with no arguments/no value is the same
as return None.
For example, if a function was built to calculate the area of a
rectangle such as the following:
Values in parenthesis can be replaced
with any other values when later being
def area(w,l): called.
return w*l
Calling the function times() with parameter
print(area(10,4))
Function with passing parameter
def greet (lang):
if lang==‘malay’:
return ‘Hai’
elif lang==‘es’:
return ‘Hola’
else:
return ‘Hello’
print (greet(‘malay’), ‘Siti’)
Parameter in Order
def add_numbers(x, y, z): # the process of
defining the
a1 = x + y #state the statement function and
parameter / argu
a2 = x + z ment
a3 = y + z
print(a1, a2, a3)
add_numbers (30, 100, 4) # pass the value into
the parameter Order
x = 30
y = 100
z=4
Call function with Parameter
print (a1, a2, a3)
Instruction to call
the function
add_numbers (30, 100, 4)
pass the value
into the function
(x, y and z)
Parameter using Keyword Argument
By using keyword argument, the parameter can
be called using its name instead of order.
def login_info (userID, katalaluan):
print (“Username: “ + userID)
print (“Password: “ + katalaluan)
login_info (”Siti”, “12345”)
login_info (katalaluan = “12345”, userID = “Siti”)
Parameter using Keyword Argument
By using keyword argument, the parameter can
be called using its name instead of order.
login_info (”Alpha”, “deltaecho”) # call by order
login_info (katalaluan = “zuluquebec”, userID =
“Beta”) # call by name
Using Loop in function
def contoh_loop (): define the
for x in range (0,10): function
print (x)
if x == 9:
We want it
return to stop at 9
print ("This is the last line")
contoh_loop()
Call function
Using if-else in function
def names(): # Define function names()
name = str(input('Enter your name: ‘)) # Set up name variable with
input
# Check whether name has a vowel
if set('aeiou').intersection(name.lower()):
print('Your name contains a vowel.')
else:
print('Your name does not contain a vowel.')
# Iterate over name
for letter in name:
print(letter)
names() # Call the function
Practice
Why should we code functions?
When/At what time Python creates a function?
What does a function return if it has no return statement in
it?