Lecture 7 - Functions
Lecture 7 - Functions
• ‘Functions’ in python
• Introduction
• Defining a Function
• Passing Arguments
• Return Values
• Passing a List
FUNCTIONS
Introduction to Function
• Function: group of statements within a program that perform specific task
• Usually one task of a large program
Functions can be executed in order to perform overall program task
• Known as divide and conquer approach
• Modularized program: program wherein each task within the program is in
its own function
Functions help break our program into smaller
and modular chunks. As our program grows
larger and larger, functions make it more
organized and manageable
Functions help break
our program into
smaller and modular
chunks. As our
Blocks of
program grows larger
codes and larger, functions
make it more
organized and
manageable
Types of functions:
Void Functions and Value-Returning Functions
• void function:
• Simply executes the statements it contains and then terminates.
• Executes the lines of code without returning a value
print(), .format()
• value-returning function:
• Designed to return values upon executes
• Executes the statements it contains, and then it returns a value back
to the statement that called it.
• The input(), int(), and float() functions are examples
of value-returning functions.
Built-in vs User-defined Functions
TRY THIS!
Write a function called fav_class() that accepts one parameter, course.
The function print a message, such as ‘My favorite class is Python’.
Call the function, making sure that you include the course name in the
function call
parameter
argument
Passing Arguments
Positional Arguments – must follow the order
Multiple
function calls
Passing Multiple Arguments in Multiple functions
Calling another function known as
fav_class with specified arguments
In the main function, it calls another function called
power()
TRY THIS!
Write a program that calculates
and display the area of a circle.
Using two functions, main and
area_circle.
In the area_circle, return the
value back to the main function
HINT: Area of a circle is r2
Returning Multiple Values
Function with Default Values
• Parameters of a function can have default values
• Default values assigned to them when no values are passed as
arguments
• Function definition format with default values:
def functionName(par1=value, par2=value)
def functionName(par1, par2, par3=value, par4=value)
Passing a List
First we define a function students() that
expects a list of name. The function loops
through the list that it receives.
TRY THIS!
Write a program that display the toppings of your pizza using a list that
contains 3 toppings. For example: ‘Your pizza has the following toppings:’
Using * to pass an arbitrary number as arguments