CEN111: Programming I: International Burch University
CEN111: Programming I: International Burch University
IBU Lecture 5
International Burch University
Lecture #5: Functions - Part 2
Calling Functions
Function name
Arguments passed into function
Return Value
() tells Python to execute the function
Even if a function takes no input, the brackets are still required
Some functions do not return a value – these are called void
Function should return a value with the keyword return
After return, Python jumps out of the function and back to the
program
2/1
Main Function main()
It is both common and a good idea to use a main function in your
programs
This is usually the starting point of a program and is run by typing:
main()
This simplifies rerunning programs and as well as passing input
values
Return values
example:
def area(radius):
temp = math.pi * radius**2
return temp
In this example the function area returns the area of a circle with the
given radius
return expression means the following:
“Return immediately from this function and use the following
expression as a return value.”
we can rewrite this function as follows
def area(radius):
return math.pi * radius**2 3/1
example: Write a function that returns the absolute value of a number
def absolute_value(x):
if x < 0:
return -x
else:
return x
This function has 2 return statements.
Since these return statements are in an alternative conditional, only one
will be executed.
As soon as a return statement executes, the function terminates without
executing any subsequent statements.
Code that appears after a return statement, or any other place the flow
of execution can never reach, is called dead code.
4/1
When writing functions with multiple paths (ie when using conditionals)
we should make sure that every possible path through the program hits a
return statement. For example:
def absolute_value(x):
if x < 0:
return -x
if x > 0:
return x
5/1
Composition
We can call one function from within another. This ability is called
composition.
example 1: Write a function that computes the distance between 2
points (x1 , y1 ) and (x2 , y2 )
example 2: Write a function that takes two points, the center of the
circle and a point on the perimeter, and computes the area of the circle.
Assume that the center point is stored in the variables xc and yc, and the
perimeter point is in xp and yp. The first step is to find the radius of the
circle, which is the distance between the two points. We just wrote a
function, distance, that does that.
6/1
We also wrote the function for the area of a circle with a given radius
def area(radius):
return math.pi * radius**2
7/1
Boolean functions
Functions can return booleans, which is often convenient for hiding
complicated tests inside functions. For example:
if is_divisible(x, y):
print ("x is divisible by y")
8/1