09-Python Function - User Defined
09-Python Function - 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:
Syntax:
def functionname(parameters/arguments):
function_statements
return [expression]
Defining a Function
def function_name():
statement (must be indented)
print(‘How are you? Let us look at some lyrics’) 1 Will be executed first by Python
Output
How are you? Let us look at some lyrics
You are my fire
The one desire
Function without argument/parameter
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
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)