0% found this document useful (0 votes)
37 views21 pages

Chapter4 - Function

asdas

Uploaded by

fzrish
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)
37 views21 pages

Chapter4 - Function

asdas

Uploaded by

fzrish
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/ 21

BERV 1313

Computer
Programming
Function
Prepared by Rosziana Binti Hashim
Learning Objective

• To know the idea of functions and why we need them.


• To know how to define a function, it’s arguments, and return statements.
• To know how to call or execute a function.

2024/2025 SEM II BERV 1313 Computer Programming 2


Function
• A function is a set of statements that take inputs, do some specific computation and produces
output.
• The idea is to put some commonly or repeatedly done task together and make a function, so
that instead or writing the same code again and again for different inputs, we call the function.
• Python provides build-in functions like print(), etc. but we can also create our own functions.
These function are called user-defined function.

2024/2025 SEM II BERV 1313 Computer Programming 3


Types of Functions
• Basically, we can divide functions into the following two types:

 Built-in functions
function that are built into Python

 User-defined functions
function defined by users themselves.

2024/2025 SEM II BERV 1313 Computer Programming 4


Defining Function
• 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.

• The statement return [ expression ] exit a function, optionally passing back an expression to the
caller. A return statement with no arguments is the same as return None.

2024/2025 SEM II BERV 1313 Computer Programming 5


Syntax
 The first statement of a function can be an optional statement-the documentation string of the
function or docstring.

 Function Syntax:
def function_name ( parameters ):
“function_docstring” #optional
function_statement
return [ expression]
 Example
def evenOdd( x ):
“A function to check if given number is even or
odd”
if ( x % 2 == 0):
print(“even”)
else :
print(“odd”)
2024/2025 SEM II BERV 1313 Computer Programming
Calling a Function
• Defining a function only give it a name, specifies the parameters that are to be included in the
function and structures the block of code.
• One the basic structure of a function is finalized, you can execute it by calling it from another
function or directly from the Python prompt.
• You must make sure that the given arguments matches the parameters specified in the
function.
• The function calling may be done before or after function definition

Example def evenOdd( x ):


“A function to check if given number is even or odd”
if ( x % 2 == 0):
print(“even”)
else :
print(“odd”)

#calling the function


evenOdd(2)
evenOdd(3)
2024/2025 SEM II BERV 1313 Computer Programming 7
Default Argument
• Defining a function only give it a name, specifies the parameters that are to be included in the
function and structures the block of code.
• One the basic structure of a function is finalized, you can execute it by calling it from another
function or directly from the Python prompt.
• You must make sure that the given arguments matches the parameters specified in the
function.
• The function calling may be done before or after function definition

Example def evenOdd( x ):


“A function to check if given number is even or odd”
if ( x % 2 == 0):
print(“even”)
else :
print(“odd”)

#calling the function


evenOdd(2)
even Odd(3)
2024/2025 SEM II BERV 1313 Computer Programming 8
Multiple Arguments
• We may specified more than one parameter to the function. Hence, effects the number of
arguments needed.

Example #multiple arguments


def printWelcome( fn, ln ):
print(“Welcome {} {}!”.format(fn, ln))

printWelcome(“Mas”, “Elyna”)

• We may specified any of the parameters with default value


Example #multiple arguments
def printWelcome( fn, ln= “Doe” ):
print(“Welcome {} {}!”.format(fn, ln))

printWelcome(“Mas”, “Elyna”)
printWelcome(“Mas”)

2024/2025 SEM II BERV 1313 Computer Programming 9


Keyword Arguments
• The idea is to allow caller to specify argument name with values so that caller does not need to
remember the order of parameters.

Example #multiple arguments


def printWelcome( fn, ln ):
print(“Welcome {} {}!”.format(fn, ln))

#call the function with key, so we don’t need


#to remember the order of parameters.

printWelcome(fn=“Mas”, ln=“Elyna”)
printWelcome(ln=“Doe”, fn=“John”)

2024/2025 SEM II BERV 1313 Computer Programming 10


Arbitrary Arguments
• If you do not know how many arguments will be passed into your function, add a * before
parameter name in the function definition.
• This way the function will receive a tuple arguments, and can access the items accordingly.

Example #multiple arguments


def printInfo( *args ):
“This function can receive a tuple arguments”
for x in args:
print(x, end=“ ”)
print(“\n-----”)

#call the function with arbitrary number of arguments

printInfo(1,2,3,4,5)
printInfo(“a”,”b”,”c”)
printInfo(“Hi”)
printInfo()

2024/2025 SEM II BERV 1313 Computer Programming 11


Arbitrary Arguments
• You can send any data types of arguments to a function (string, number, list, dictionary etc.),
and it will be treated as the same data type inside the function.

Example #passing list as arguments


def printFunc( food ):
for x in food:
print(x)

#call the function, giving a list as argument

fruits = [“apple”, “banana”, “cherry”]


printFunc(fruits)

dessert = [“cake”, “pie”, “jelly” ]


printFunc(dessert)

2024/2025 SEM II BERV 1313 Computer Programming 12


Return Value
• To let a function return a value, use the return statement:

Example #return value


def addTwo( x ):
“This function will add the argument with 2”

return x+2

#example: call the function and print the returned value

print(addTwo(3))

#example: call the function and use the returned value

Y = addTwo(14)
Z = y*3
print(“(14+2)*3 = ”, Z)

2024/2025 SEM II BERV 1313 Computer Programming 13


The pass Statement
• Function definitions cannot be empty, but if you for some reason, have a function definition
with no content, put in the pass statement to avoid getting error.
• Pass statement also use as place holder for future code.

Example #pass
def myfunc ( ):

pass

#call a function that do nothing

myfunc()

2024/2025 SEM II BERV 1313 Computer Programming 14


Example
• Question: Create a function to calculate area of circle with given radius as input. Create another
function to print the info of a circle, given the radius and area as input. Call these functions with
suitable arguments.
#import math library to get PI value
import math Modify the codes to so that it can get the input of radius from
user and do all required operation 3 times in a loop.
#define function
def calculateArea ( radius ):
“This function calculate area of a circle from given radius”
area = math.pi * radius *radius
return area

def printInfo ( radius, area ):


“This function print the info of circle with given parameters”
print(“Area of circle with radius {} cm is {:0.2f} sq.cm”.
Format(radius, area))
#call a function
r = 12
printInfo(r, calculateArea(r))

2024/2025 SEM II BERV 1313 Computer Programming 15


Exercise
#Create a function name my_function

_______________________________________________
Exercise 1
print(“Hello”)

#Write a statement to execute my_function in Exercise 1

_______________________________________________
Exercise 2

#Inside a function with two parameters, print the first parameter.

def my_function(fname, lname):


print(________________) Exercise 3
2024/2025 SEM II BERV 1313 Computer Programming 16
Exercise
#return the value of x+5
def calc(x):

__________________________________ Exercise 4

#Create an arbitrary argument function that will print all given arguments

def printArgs(____________):
____________________
________________________
Exercise 5
printArgs(23, 34, 45)

#The second parameter of this function has a default value of 5

Def fun(________________):
print(x,y) Exercise 6
2024/2025 SEM II BERV 1313 Computer Programming 17
Exercise
1. Create a function named myfun that accepts 1 parameter value, x.

2. Inside the function, return the value of 20% of x.

3. Call the function, giving the value of 43.5 as an input.

4. Print the return result.

5. Example output:
20% of 43.5 is 8.7

2024/2025 SEM II BERV 1313 Computer Programming 18


Exercise
1. Create a function named getGrade that can return the grade of a user. Given the mark
Mark Grade
≥80 A
60-79 B
40-59 C
≤39 F

2. Get input from 4 users to get their name and marks.


3. For each user, call the getGrade function to get their grades, provided the marks
4. Example output:
5. Hi Adam. Your grade is B

2024/2025 SEM II BERV 1313 Computer Programming 19


Exercise
1. Create a list named myList with the value of 5,3,6,7,2.
2. Create a function named double. This function accepts a list as a parameter. It will calculate the
double amount of each given number in the list, then print the result.
3. Call this function by giving mylist as arguments.

2024/2025 SEM II BERV 1313 Computer Programming 20


Exercise
1. Create a function named calcArea that can calculate and return the area of a rectangle, given
the width and length of rectangle.
2. Create another function named calcVolume that will return the value of a cuboid’s volume,
given the area and height
The formula for cuboid’s volume is:
CuboidVolume = RectangleArea * Height

3. Call these functions accordingly to print the information of a cuboid


4. example output:
width :15
length : 20
height : 10
rectangle area : 300
cuboid volume : 3000

2024/2025 SEM II BERV 1313 Computer Programming 21

You might also like