0% found this document useful (0 votes)
6 views75 pages

Chapter 5

Chapter 5 covers the concept of functions in programming, explaining their definition, types (void and value-returning), and the benefits of modular programming. It discusses the importance of local and global variables, passing arguments, and the use of the math module for mathematical operations. Additionally, it provides insights on designing programs with functions, including flowcharts, IPO charts, and the organization of code through modules.

Uploaded by

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

Chapter 5

Chapter 5 covers the concept of functions in programming, explaining their definition, types (void and value-returning), and the benefits of modular programming. It discusses the importance of local and global variables, passing arguments, and the use of the math module for mathematical operations. Additionally, it provides insights on designing programs with functions, including flowcharts, IPO charts, and the organization of code through modules.

Uploaded by

mehad20062006
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CHAPTER 5

Functions
Topics
q Introduction to Functions
q Defining and Calling a Void Function
q Designing a Program to Use Functions
q Local Variables
q Passing Arguments to Functions
q Global Variables and Global Constants
q Introduction to Value-Returning Functions: Generating
Random Numbers
q Writing Your Own Value-Returning Functions
q The math Module
q Storing Functions in Modules
Introduction to Functions
• Function: group of statements within a program that
perform as 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
Benefits of Modularizing a Program with
Functions
q The benefits of using functions include:
• Simpler code
• Code reuse
o write the code once and call it multiple times
• Better testing and debugging
o Can test and debug each function individually
• Faster development
• Easier facilitation of teamwork
o Different team members can write different functions
Void Functions and Value-Returning
Functions
• A void function:
• Simply executes the statements it contains and then
terminates.

• A value-returning function:
• Executes the statements it contains, and then it returns a
value back to the statement that called it.
o The input, int, and float functions are examples of value-
returning functions.
Defining and Calling a Function

qFunctions are given names


• Function naming rules:
o Cannot use key words as a function name
o Cannot contain spaces
o First character must be a letter or underscore
o All other characters must be a letter, number or underscore
o Uppercase and lowercase characters are distinct
Defining and Calling a Function
q Function name should be descriptive of the task carried
out by the function
• Often includes a verb
q Function definition: specifies what function does
def function_name():
statement
statement
q Function header: first line of function
• Includes keyword def and function name, followed by
parentheses and colon
q Block: set of statements that belong together as a group
• Example: the statements included in a function
Defining and Calling a Function
q Call a function to execute it
• When a function is called:
o Interpreter jumps to the function and executes statements
in the block
o Interpreter jumps back to part of program that called the
function
ü Known as function return
q Example
def message():
print('I am Arthur,')
print('King of the Britons.')
message()
q main function: called when the program starts
• Calls other functions when they are needed
• Defines the mainline logic of the program
Example 5-1
Example 5-2
Indentation in Python
q Each block must be indented
• Lines in block must begin with the same number of spaces
o Use tabs or spaces to indent lines in a block, but not both as
this can confuse the Python interpreter
o IDLE automatically indents the lines in a block

• Blank lines that appear in a block are ignored


Designing a Program to Use
Functions
q In a flowchart, function call shown as rectangle with
vertical bars at each side
• Function name written in the symbol
• Typically draw separate flow chart for each function in the
program
• End terminal symbol usually reads Return

q Top-down design: technique for breaking algorithm into


functions
Flowchart for Program 5-2
Designing a Program to Use Functions
(cont’d.)
• Hierarchy chart: depicts relationship between functions
• AKA structure chart
• Box for each function in the program, Lines connecting
boxes illustrate the functions called by each function
• Does not show steps taken inside a function
• Use input function to have program wait for user to press
enter
Designing a Program to Use
Functions (cont’d.)
Example
5-3
Using Pass Keyword
q Sometimes when you are initially writing a
program’s code, you know the names of the
def step1():
functions you plan to use, but you might not know
pass
all the details of the code that will be in those def step2():
functions. When this is the case, you can use the pass
pass keyword to create empty functions. def step3():
q Later, when the details of the code are known, you pass
can come back to the empty functions and replace def step4():
the pass keyword with meaningful code. pass

q For example, when we were writing the code for


Program 5-3, we could have initially written empty
function definitions for the step1, step2, step3, and
step4 functions, as shown here:
Local Variables
q Local variable: variable that is assigned a value inside a
function
• Belongs to the function in which it was created
o Only statements inside that function can access it, error will
occur if another function tries to access the variable
q Scope: the part of a program in which a variable may be
accessed
• For local variable: function in which created
q Local variable cannot be accessed by statements inside its
function which precede its creation
q Different functions may have local variables with the same
name
• Each function does not see the other function’s local
variables, so no confusion
Example
5-4

q This program has two functions: main and get_name. In line 8, the name
variable is assigned a value that is entered by the user. This statement is
inside the get_name function, so the name variable is local to that
function. This means that the name variable cannot be accessed by
statements outside the get_name function.
q The main function calls the get_name function in line 3. Then, the
statement in line 4 tries to access the name variable. This results in an
error because the name variable is local to the get_name function, and
statements in the main function cannot access it.
Example 5-5
Passing Arguments to Functions
q Argument: piece of data that is sent into a function
• Function can use argument in calculations
• When calling the function, the argument is placed in
parentheses following the function name
Passing Arguments to Functions
• Parameter variable: variable that is assigned the value
of an argument when the function is called
• The parameter and the argument reference the same
value
• General format:
def function_name(parameter):
• Scope of a parameter: the function in which the
parameter is used
Example 5-6
Passing Multiple Arguments
• Python allows writing a function that accepts multiple
arguments
• Parameter list replaces single parameter
• Parameter list items separated by comma
• Arguments are passed by position to corresponding
parameters
• First parameter receives value of first argument, second
parameter receives value of second argument, etc.
Example 5-8
Passing Multiple Arguments
(cont’d.)
Example 5-9
Example
5-10
Making Changes to Parameters
• Changes made to a parameter value within the function
do not affect the argument
• Known as pass by value
• Provides a way for unidirectional communication between
one function and another function
• Calling function can communicate with called function
Making Changes to Parameters
(cont’d.)
Making Changes to Parameters
(cont’d.)
• Figure 5-18
• The value variable passed to the change_me function
cannot be changed by it
Keyword Arguments
q Keyword argument: argument that specifies which
parameter the value should be passed to
• Position when calling function is irrelevant
• General Format:
function_name(parameter=value)

q Possible to mix keyword and positional arguments


when calling a function
• Positional arguments must appear first
Example
5-11
Example 5-12
Global Variables and Global
Constants
• Global variable: created by assignment statement
written outside all the functions
• Can be accessed by any statement in the program file,
including from within a function
• If a function needs to assign a value to the global variable,
the global variable must be redeclared within the function
o General format: global variable_name
Program 5-13
Program 5-14
Global Variables and Global
Constants (cont’d.)
q Reasons to avoid using global variables:
• Global variables making debugging difficult
o Many locations in the code could be causing a wrong
variable value

• Functions that use global variables are usually dependent


on those variables
o Makes function hard to transfer to another program

• Global variables make a program hard to understand


Global Constants
• Global constant: global name that references a value
that cannot be changed
• Permissible to use global constants in a program
• To simulate global constant in Python, create global
variable and do not re-declare it within functions
Introduction to Value-Returning
Functions: Generating Random Numbers
• void function: group of statements within a program for
performing a specific task
• Call function when you need to perform the task
• Value-returning function: similar to void function,
returns a value
• Value returned to part of program that called the function
when function finishes executing
Standard Library Functions and
the import Statement
q Standard library: library of pre-written functions that
comes with Python
• Library functions perform tasks that programmers commonly
need
• Example: print, input, range
• Viewed by programmers as a “black box”
q Some library functions built into Python interpreter
• To use, just call the function
qModules: files that stores functions of the standard
library
• Help organize library functions not built into the interpreter
• Copied to computer when you install Python
Standard Library Functions and
the import Statement (cont’d.)
• To call a function stored in a module, need to write
an import statement
• Written at the top of the program
• Format: import module_name
Generating Random Numbers
• Random number are useful in a lot of programming
tasks
• random module: includes library functions for working
with random numbers
• Dot notation: notation for calling a function belonging
to a module
• Format: module_name.function_name()
Generating Random Numbers
(cont’d.)
q randint function: generates a random number in the
range provided by the arguments
• Returns the random number to part of program that called
the function
• Returned integer can be used anywhere that an integer
would be used
• You can experiment with the function in interactive mode
Generating Random Numbers
(cont’d.)
Example 5-16
Example
5-17
Example 5-18
Generating Random Numbers
q randrange function: similar to range function, but returns
randomly selected integer from the resulting sequence
• Same arguments as for the range function
number = [Link](10)
o assigns a random number in the range of 0 through 9 to the number
variable.
number = [Link](5,10)
o a random number in the range of 5 through 9 will be assigned to
number.
number = [Link](0, 101, 10)
o returns a randomly selected value from the following sequence
of numbers: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Generating Random Numbers
q random function: returns a random float in the range of
0.0 and 1.0
• Does not receive arguments

number = [Link]()
q uniform function: returns a random float but allows
user to specify range
number = [Link](1.0, 10.0)
o In this statement, the uniform function returns a random floating-
point number in the range of 1.0 through 10.0 and assigns it to the
number variable.
Random Number Seeds
q Random number created by functions in random
module are actually pseudo-random numbers
q Seed value: initializes the formula that generates
random numbers
• Need to use different seeds in order to get different series
of random numbers
o By default uses system time for seed
o Can use [Link]() function to specify desired seed
value
Writing Your Own Value-Returning
Functions
q To write a value-returning function, you write a simple
function and add one or more return statements
• Format: return expression
o The value for expression will be returned to the part of the
program that called the function
• The expression in the return statement can be a complex
expression, such as a sum of two variables or the result of
another value- returning function
How to Use Value-Returning
Functions
q Value-returning function can be useful in specific
situations
• Example: have function prompt user for input and return
the user’s input
• Simplify mathematical expressions
• Complex calculations that need to be repeated throughout
the program
q Use the returned value
• Assign it to a variable or use as an argument in another
function
Example
5-21
Using IPO Charts
q IPO chart: describes the input, processing, and output
of a function
• Tool for designing and documenting functions
• Typically laid out in columns
• Usually provide brief descriptions of input, processing, and
output, without going into details
o Often includes enough information to be used instead of a
flowchart
Using IPO Charts (cont’d.)
Example
5-23
Example 5-23
Example 5-23
Example 5-23
Returning Strings
• You can write functions that return strings
• For example:
Returning Boolean Values
q Boolean function: returns either True or False
• Use to test a condition such as for decision and repetition
structures
o Common calculations, such as whether a number is even,
can be easily repeated by calling a function
• Use to simplify complex input validation code
Returning Multiple Values
q In Python, a function can return multiple values
• Specified after the return statement separated by
commas
o Format: return expression1, expression2,
etc.

• When you call such a function in an assignment statement,


you need a separate variable on the left side of the =
operator to receive each returned value
Returning None from a Function
q Python has a special built-in value named None that is
used to represent no value. Sometimes it is useful to
return None from a function to indicate that an error has
occurred. For example, consider the following function:
def divide(num1, num2):
return num1 / num2
The math Module
• math module: part of standard library that contains
functions that are useful for performing mathematical
calculations
• Typically accept one or more values as arguments,
perform mathematical operation, and return the result
• Use of module requires an import math statement
The math Module (cont’d.)
The math Module (cont’d.)
q The math module defines variables pi and e, which
are assigned the mathematical values for pi and e
• Can be used in equations that require these values, to get
more accurate results

q Variables must also be called using the dot notation


• Example:
circle_area = [Link] * radius**2
Storing Functions in Modules
q In large, complex programs, it is important to keep code
organized
q Modularization: grouping related functions in modules
• Makes program easier to understand, test, and maintain
• Make it easier to reuse code for multiple different
programs
o Import the module containing the required function to each
program that needs it
Example 5-25
Storing Functions in Modules
(cont’d.)
q Module is a file that contains Python code
• Contains function definition but does not contain calls to
the functions
o Importing programs will call the functions

q Rules for module names:


• File name should end in .py
• Cannot be the same as a Python keyword
q Import module using import statement
Menu Driven Programs
q Menu-driven program: displays a list of operations on
the screen, allowing user to select the desired
operation
• List of operations displayed on the screen is called a menu

q Program uses a decision structure to determine the


selected menu option and required operation
• Typically repeats until the user quits
Summary
q This chapter covered:
• The advantages of using functions
• The syntax for defining and calling a function
• Methods for designing a program to use functions
• Use of local variables and their scope
• Syntax and limitations of passing arguments to functions
• Global variables, global constants, and their advantages and
disadvantages
Summary (cont’d.)
• Value-returning functions, including:
o Writing value-returning functions
o Using value-returning functions

o Functions returning multiple values

• Using library functions and the import statement


• Modules, including:
o The random and math modules

o Grouping your own functions in modules

You might also like