08-Python Function user defined edited
08-Python Function user defined edited
SEKOLAH PENDIDIKAN,
FAKULTI SAINS SOSIAL DAN KEMUANUSIAAN, UTM 2020
Introduction
A function is a block of organized, reusable code that is
used to perform a single, related action. Functions provides
better modularity for your application and a high degree of
code reusing.
As you already know, Python gives you many built-in
functions like print() etc. but you can also create your own
functions.
These functions are called user-defined functions.
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 first statement of a function can be an optional statement
- the documentation string of the function or docstring.
The code block within every function starts with a colon (:)
and is indented.
The statement return [expression] exits a function, optionally
passing back an expression to the caller. A return statement
with no arguments is the same as return None.
Defining a Function
Python keyword cant 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 ):
function_statements
return [expression]
Defining a Function
def function_name):
statement (must be indent)
call the 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)