0% found this document useful (0 votes)
14 views

Chapter 5 part 1 pfe

The document explains the concept of functions in programming, detailing their structure, how to define and call them, and the significance of arguments and return values. It also covers the implementation of functions without return values, the importance of reusable functions, debugging techniques, and introduces recursive functions. Examples are provided to illustrate these concepts, including function definitions and testing.

Uploaded by

thetechfluxyt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Chapter 5 part 1 pfe

The document explains the concept of functions in programming, detailing their structure, how to define and call them, and the significance of arguments and return values. It also covers the implementation of functions without return values, the importance of reusable functions, debugging techniques, and introduces recursive functions. Examples are provided to illustrate these concepts, including function definitions and testing.

Uploaded by

thetechfluxyt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 30

Functions

1
Functions as Black Boxes

• A function is a sequence of instructions with a name. You have


already encountered several functions. For example, the round
function, which was introduced in Chapter 2, contains
instructions to round a floating-point value to a specified number
of decimal places.

• You call a function in order to execute its instructions. For


example, consider the following program statement:

price = round(6.8275, 2) # Sets result to 6.83


• By using the expression round(6.8275, 2), your program calls the
round function, asking it to round 6.8275 to two decimal digits.
The instructions of the round function execute and compute the
result. The round function returns its result back to where the
function was called and your program resumes execution.

2
Argument and return value

• These values are called the arguments of the function call. Note
that they are not necessarily inputs provided by a human user.
They are simply the values for which we want the function to
compute a result.
• The “output” that the round function computes is called the
return value.

• Functions can receive multiple arguments, but they return only


one value. It is also possible to have functions with no
arguments. An example is the random function that requires no
argument to produce a random number.

3
Arguments and Return Value

4
Return Value

price = round(6.8275, 2)
•When the round function returns its result, the return value is
stored in the variable price.
•Do not confuse returning a value with producing program output.
If you want the return value to be printed, you need to add a
statement such as print(price).

5
Implementing and Testing
Functions
• We will start with a very simple example: a function to compute
the volume of a cube with a given side length.

When writing this function, you need to


• Pick a name for the function (cubeVolume).
• Define a variable for each argument (sideLength). These
variables are called the parameter variables.
• Put all this information together along with the def reserved
word to form the first line of the function’s definition:

def cubeVolume(sideLength) :

6
Defining a Function

def cubeVolume(sideLength) :
•This line is called the header of the function. Next, specify the
body of the function.
•The body contains the statements that are executed when the
function is called.
•The volume of a cube of side length s is s × s × s = s3. However,
for greater clarity, our parameter variable has been called
sideLength, not s, so we need to compute sideLength ** 3.
•We will store this value in a variable called volume:
volume = sideLength ** 3
•In order to return the result of the function, use the return
statement:

return volume

7
Defining a function

• A function is a compound statement, which requires the


statements in the body to be indented to the same level. Here is
the complete function:

def cubeVolume(sideLength) :
volume = sideLength ** 3
return volume

8
Testing a Function

• In the preceding section, you saw how to write a function. If you


run a program containing just the function definition, then nothing
happens. After all, nobody is calling the function.
• In order to test the function, your program should contain
• The definition of the function.
• Statements that call the function and print the result.
Here is such a program:
def cubeVolume(sideLength) :
volume = sideLength ** 3
return volume
result1 = cubeVolume(2)
result2 = cubeVolume(10)
print("A cube with side length 2 has volume", result1)
print("A cube with side length 10 has volume", result2)

9
Function Calling

• Note that the function returns different results when it is called


with different arguments.
• Consider the call cubeVolume(2). The argument 2 corresponds to
the sideLength parameter variable. Therefore, in this call,
sideLength is 2. The function computes sideLength ** 3, or 2 **
3. When the function is called with a different argument, say 10,
then the function computes 10 ** 3.

10
Programs with functions

• For example, the following will produce a compile-time error:

print(cubeVolume(10))
def cubeVolume(sideLength) :
volume = sideLength ** 3
return volume

• The compiler does not know that the cubeVolume function will
be defined later in the program.

11
• However, a function can be called from within another function before the
former has been defined. For example, the following is perfectly legal:
def main() :
result = cubeVolume(2)
print("A cube with side length 2 has volume", result)
def cubeVolume(sideLength) :
volume = sideLength ** 3
return volume
main()

• Note that the cubeVolume function is called from within the main function
even though cubeVolume is defined after main. To see why this is not a
problem, consider the flow of execution. The definitions of the main and
cubeVolume functions are processed. The statement in the last line is not
contained in any function. Therefore, it is executed directly. It calls the
main function. The body of the main function executes, and it calls
cubeVolume, which is now known.

12
Parameter Passing

• When a function is called, variables are created for receiving the


function’s arguments. These variables are called parameter
variables. (Another commonly used term is formal
parameters.) The values that are supplied to the function when
it is called are the arguments of the call. (These values are also
commonly called the actual parameters.)

• Each parameter variable is initialized with the corresponding


argument.

13
Return Values

• You use the return statement to specify the result of a function.


In the preceding examples, each return statement returned a
variable. However, the return statement can return the value of
any expression.
• Instead of saving the return value in a variable and returning the
variable, it is often possible to eliminate the variable and return
the value of a more complex expression:

def cubeVolume(sideLength) :
return sideLength ** 3

14
Return Function

• When the return statement is processed, the function exits


immediately. Some Programmers find this behavior convenient
for handling exceptional cases at the beginning of the function:

def cubeVolume(sideLength) :
if sideLength < 0 :
return 0
# Handle the regular case.
.
.
.

15
Functions Without Return Values

• Sometimes, you need to carry out a sequence of instructions


that does not yield a value. If that instruction sequence occurs
multiple times, you will want to package it into a function.

• Here is a typical example: Your task is to print a string in a box,


like this:

-------
!Hello!
-------

16
Functions Without Return Values

• However, different strings can be substituted for Hello. A


function for this task can be defined as follows:
• def boxString(contents) :
• Now you develop the body of the function in the usual way, by
formulating a general algorithm for solving the task.

Print a line that contains the - character n + 2 times,


where n is the length of the string.
Print a line containing the contents, surrounded with a ! to
the left and right.
Print another line containing the - character n + 2 times.

17
Functions Without Return Values

• Here is the function implementation:

## Prints a string in a box.


# @param contents the string to enclose in a
box
#
def boxString(contents) :
n = len(contents) :
print("-" * (n + 2))
print("!" + contents + "!")
print("-" * (n + 2))
18
Calling function with no return
statement
• Note that this function doesn’t compute any value. It performs
some actions and then returns to the caller. Actually, the
function returns a special value, called None, but there is nothing
that you can do with that value.

• Because there is no useful return value, don’t use boxString in


an expression. You can call

boxString("Hello")

• but don’t call

result = boxString("Hello") # No––boxString doesn’t return


a useful result.

19
Using return for argument validation

• If you want to return from a function that does not compute a


value before reaching the end, you use a return statement
without a value. For example,

def boxString(contents) :
n = len(contents)
if n == 0 :
return # Return immediately
print("-" * (n + 2))
print("!" + contents + "!")
print("-" * (n + 2))

20
Lets try to answer some book
questions
• How do you generate the following printout, using the boxString
function?
-------
!Hello!
-------
-------
!World!
-------
• What is wrong with the following statement?
print(boxString("Hello"))

• Implement a function shout that prints a line consisting of a string


followed by three exclamation marks. For example, shout("Hello")
should print Hello!!!. The function should not return a value.

21
Lets try to answer some book
questions
• How would you modify the boxString function to leave a space
around the string that is being boxed, like this:
---------
! Hello !
---------

22
23
Reusable Functions

• When you write nearly identical code or pseudocode multiple


times, either in the same program or in separate programs,
consider introducing a function. Here is a typical example of code
replication:
hours = int(input("Enter a value between 0 and 23: "))
while hours < 0 or hours > 23 :
print("Error: value out of range.")
hours = int(input("Enter a value between 0 and 23: "))
minutes = int(input("Enter a value between 0 and 59: "))
while minutes < 0 or minutes > 59 :
print("Error: value out of range.")
minutes = int(input("Enter a value between 0 and 59: "))
• This program segment reads two variables, making sure that each
of them is within a certain range. It is easy to extract the common
behavior into a function:

24
Reusable Functions

def readIntUpTo(high) :
value = int(input("Enter a value between 0 and " +
str(high) + ": "))
while value < 0 or value > high :
print("Error: value out of range.")
value = int(input("Enter a value between 0 and "
+ str(high) + ": "))
return value

•Then use this function twice:


hours = readIntUpTo(23)
minutes = readIntUpTo(59)

25
Book problem discussion

Consider the following function that computes compound interest


for an account with an initial balance of $10,000 and an interest
rate of 5 percent:
def balance(years) :
return 10000 * (1.05 ** years)
How can you make this function more reusable?

The comment explains what the following loop does. Use a


function instead.
# Counts the number of spaces
spaces = 0
for char in userInput :
if char == " " :
spaces = spaces + 1

26
Using a Debugger

• As you have undoubtedly realized by now, computer programs


rarely run perfectly the first time. At times, it can be quite
frustrating to find the errors, or bugs, as they are called by
programmers.
• Of course, you can insert print statements into your code that show
the program flow and values of key variables. You then run the
program and try to analyze the printout.
• But if the printout does not clearly point to the problem, you need
to add and remove print statements and run the program again.
That can be a time-consuming process.

• Modern development environments contain a debugger, a program


that helps you locate bugs by letting you follow the execution of a
program. You can stop and restart the program and see the
contents of variables whenever the program is temporarily
stopped. At each stop, you can decide how many program steps to
run until the next stop.

27
Debugger

28
Debugger essential

• Once you have started the debugger, you can go a long way with just four
debugging commands:
• “set breakpoint”, “run until breakpoint”, “step over”, and “step inside”.
The names and keystrokes or mouse clicks for these commands differ
between debuggers, but all debuggers support these basic commands.
• When you start the debugger, it runs at full speed until it reaches a
breakpoint. Then execution stops. The line containing the breakpoint that
causes the stop is displayed, but it has not yet been executed.
• You can now inspect variables and step through the program a line at a
time, or continue running the program at full speed until it reaches the
next breakpoint. When the program terminates, the debugger stops as
well.
• Running to a breakpoint gets you there speedily, but you don’t know what
the program did along the way. For a better understanding of the program
flow, you can step through the program a line at a time. One command,
usually called “step into”, steps inside function calls, and another
command, called “step over” skips over function calls. You should step
into a function to check whether it carries out its job correctly. Step over a
function if you know it works correctly.

29
Recursive Functions

• Here is a typical example. We want to print triangle patterns like


this:
[]
[][]
[][][]
[][][][]

• Specifically, our task is to provide a recursive function


def printTriangle(sideLength) :
if sideLength < 1 :
return
printTriangle(sideLength - 1)
print("[]" * sideLength)

30

You might also like