0% found this document useful (0 votes)
53 views79 pages

ST1 Week 05 Lecture New Updated

The lecture covers the fundamentals of writing functions in Python, including defining and calling void and value-returning functions, managing local and global variables, and using modules. It emphasizes the benefits of modular programming, such as code reuse and easier debugging, and provides examples of algorithms and pseudocode for practical applications. Additionally, it introduces the use of standard library functions and random number generation, along with best practices for designing and documenting functions.
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)
53 views79 pages

ST1 Week 05 Lecture New Updated

The lecture covers the fundamentals of writing functions in Python, including defining and calling void and value-returning functions, managing local and global variables, and using modules. It emphasizes the benefits of modular programming, such as code reuse and easier debugging, and provides examples of algorithms and pseudocode for practical applications. Additionally, it introduces the use of standard library functions and random number generation, along with best practices for designing and documenting functions.
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/ 79

ST1 Week 5 Lecture

Writing Functions in Python


Topics (1 of 2)
• Introduction to Functions
• Defining and Calling a Void Function
• Designing a Program to Use Functions
• Local Variables
• Passing Arguments to Functions
• Global Variables and Global Constants
• Turtle Graphics: Modularizing Code with Functions
Topics (2 of 2)
• Introduction to Value-Returning Functions: Generating
Random Numbers
• Writing Your Own Value-Returning Functions
• The math Module
• Storing Functions in Modules
Introduction to Functions (1 of 2)
• 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
Introduction to Functions (2 of 2)

Figure 5-1 Using functions to divide and conquer a large task


Benefits of Modularizing a Program
with Functions
• The benefits of using functions include:
– Simpler code
– Code reuse
 write the code once and call it multiple times
– Better testing and debugging
 Can test and debug each function individually
– Faster development
– Easier facilitation of teamwork
 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.
 The input, int, and float functions are examples of
value-returning functions.
Defining and Calling a Function (1 of 5)
• Functions are given names
– Function naming rules:
 Cannot use keywords as a function name
 Cannot contain spaces
 First character must be a letter or underscore
 All other characters must be a letter, number or
underscore
 Uppercase and lowercase characters are distinct
Defining and Calling a Function (2 of 5)
• Function name should be descriptive of the task
carried out by the function
– Often includes a verb
• Function definition: specifies what function does
def function_name():
statement
statement
Defining and Calling a Function (3 of 5)
• Function header: first line of function
– Includes keyword def and function name, followed by
parentheses and colon
• Block: set of statements that belong together as a
group
– Example: the statements included in a function
Defining and Calling a Function (4 of 5)
• Call a function to execute it
– When a function is called:
 Interpreter jumps to the function and executes
statements in the block
 Interpreter jumps back to part of program that called the
function
– Known as function return
Defining and Calling a Function (5 of 5)
• main function: called when the program starts
– Calls other functions when they are needed
– Defines the mainline logic of the program
Indentation in Python
• Each block must be indented
– Lines in block must begin with the same number of
spaces
 Use tabs or spaces to indent lines in a block, but not
both as this can confuse the Python interpreter
 IDLE automatically indents the lines in a block
– Blank lines that appear in a block are ignored
Designing a Program to Use Functions
(1 of 3)

• 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

• Top-down design: technique for breaking algorithm


into functions
Designing a Program to Use Functions
(2 of 3)

• 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
Example: Defining and Using Functions
Professional Appliance Service, Inc. offers maintenance and repair
services for household appliances. The owner wants to give each of the
company’s service technicians a small handheld computer that displays
step-by-step instructions for many of the repairs that they perform. To
see how this might work, the owner has asked you to develop a
program/chatbot that displays the following instructions for
disassembling an Acme laundry dryer:
Step 1: Unplug the dryer and move it away from the wall.
Step 2: Remove the six screws from the back of the dryer.
Step 3: Remove the dryer’s back panel.
Step 4: Pull the top of the dryer straight up.
Requirements Specification
• During your interview with the owner, you
determine that your chatbot program should
display the steps one at a time.
• You decide that after each step is displayed, the
user will be asked to press the Enter key to see
the next step.
• Here is the algorithm in pseudocode:
Algorithm / Pseudocode
Algorithm in pseudo code

• This algorithm lists the top level of tasks that the


program needs to perform and becomes the basis of
the program’s main function.
Hierarchy chart (Organisation of functions)

Figure 5-10 A hierarchy chart


Coding and Testing
• Iterative coding and testing
• Demo
Using the pass Keyword
• You can use the pass keyword to create empty
functions
• The pass keyword is ignored by the Python
interpreter
• This can be helpful when designing a program

def step1():
pass

def step2():
pass
Local Variables (1 of 2)
• Local variable: variable that is assigned a value inside
a function
– Belongs to the function in which it was created
 Only statements inside that function can access it, error
will occur if another function tries to access the variable
• Scope: the part of a program in which a variable may
be accessed
– For local variable: function in which created
Local Variables (2 of 2)
• Local variable cannot be accessed by statements
inside its function which precede its creation
• Different functions may have local variables with the
same name
– Each function does not see the other function’s local
variables, so no confusion
Passing Arguments to Functions (1 of 4)
• 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 (2 of 4)

Figure 5-13 The value variable is passed as an argument


Passing Arguments to Functions (3 of 4)
• 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
Passing Arguments to Functions (4 of 4)

Figure 5-14 The value variable and the number parameter reference the same value
Passing Multiple Arguments (1 of 2)
• 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.
Passing Multiple Arguments (2 of 2)

Figure 5-16 Two arguments passed to two parameters


Making Changes to Parameters (1 of 3)
• 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 (2 of 3)

Figure 5-17 The value variable is passed to the change_me function


Making Changes to Parameters (3 of 3)
• Figure 5-18
– The value variable passed to the change_me function
cannot be changed by it

Figure 5-18 The value variable is passed to the change_me function


Example: Passing an Argument to a
Function
• Cups to Ounces converter program
Problem: Your friend Michael runs a catering company. Some of the
ingredients that his recipes require are measured in cups. When he goes
to the grocery store to buy those ingredients, however, they are sold only
by the fluid ounce. He has asked you to write a simple program that
converts cups to fluid ounces.
Algorithm Design/Pseudo code: This step identified the top level of tasks that
the program needs to perform and becomes the basis of the program’s main
function.

1. Display an introductory screen that explains what the program does.

2. Get the number of cups.

3. Convert the number of cups to fluid ounces and display the result.
Hierarchy chart
Global Variables and Global Constants
(1 of 2)

• 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
 General format: global variable_name
Coding and testing
• Here are summaries of each function in the hierarchy
chart:
• Intro. This function will display a message on the screen
that explains what the program does.
• cups_to_ounces. This function will accept the number of
cups as an argument and calculate and display the
equivalent number of fluid ounces.
• In addition to calling these functions, the main function will
ask the user to enter the number of cups. This value will
be passed to the cups_to_ounces function.
• Demo
Global Variables and Global Constants
(2 of 2)

• Reasons to avoid using global variables:


– Global variables making debugging difficult
 Many locations in the code could be causing a wrong
variable value
– Functions that use global variables are usually
dependent on those variables
 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 (1 of 3)
• 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”

• Some library functions built into Python interpreter


– To use, just call the function
Example
• Problem: Marilyn works for Integrated Systems, Inc., a software company that
has a reputation for providing excellent fringe benefits. One of their benefits is
a quarterly bonus that is paid to all employees. Another benefit is a retirement
plan for each employee. The company contributes 5 percent of each
employee’s gross pay and bonuses to their retirement plans. Marilyn wants
you to write a program that will calculate the company’s contribution to an
employee’s retirement account for a year. She wants the program to show the
amount of contribution for the employee’s gross pay and for the bonuses
separately.
• Algorithm Design/Pseudo code for the program:
– Get the employee's annual gross pay.
– Get the amount of bonuses paid to the employee.
– Calculate and display the contribution for the gross pay.
– Calculate and display the contribution for the bonuses.

• Coding/Testing
Standard Library Functions and the
import Statement (2 of 3)
• Modules: files that stores functions of the standard
library
– Help organize library functions not built into the
interpreter
– Copied to computer when you install Python
• 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
Standard Library Functions and the
import Statement (3 of 3)

Figure 5-19 A library function viewed as a black box


Generating Random Numbers (1 of 5)
• 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 (2 of 5)
• 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 (3 of 5)

Figure 5-20 A statement that calls the random function


Generating Random Numbers (4 of 5)

Figure 5-21 The random function returns a value

Figure 5-22 Displaying a random number


Generating Random Numbers (5 of 5)
• randrange function: similar to range function, but
returns randomly selected integer from the resulting
sequence
– Same arguments as for the range function
• random function: returns a random float in the range
of 0.0 and 1.0
– Does not receive arguments
• uniform function: returns a random float but allows
user to specify range
Random Number Seeds
• Random number created by functions in random
module are actually pseudo-random numbers
• Seed value: initializes the formula that generates
random numbers
– Need to use different seeds in order to get different
series of random numbers
 By default uses system time for seed
 Can use random.seed() function to specify desired
seed value
Example: Dice rolling
• Problem: Dr. Kimura teaches an introductory statistics class and has
asked you to write a program that he can use in class to simulate the
rolling of dice. The program should randomly generate two numbers in
the range of 1 through 6 and display them.
• Algorithm Design/Pseudocode: In your interview with Dr. Kimura,
you learn that he would like to use the program to simulate several
rolls of the dice, one after the other.
– While the user wants to roll the dice:
– Display a random number in the range of 1 through 6
– Display another random number in the range of 1 through 6
– Ask the user if he or she wants to roll the dice again

• Coding/Testing
Writing Your Own Value-Returning
Functions (1 of 2)
• To write a value-returning function, you write a simple
function and add one or more return statements
– Format: return expression
 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
Writing Your Own Value-Returning
Functions (2 of 2)

Figure 5-23 Parts of the function


How to Use Value-Returning Functions
• 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
• Use the returned value
– Assign it to a variable or use as an argument in another
function
Using IPO Charts (1 of 2)
• 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
 Often includes enough information to be used instead of
a flowchart
Using IPO Charts (2 of 2)

Figure 5-25 IPO charts for the getRegularPrice and discount functions
Returning Strings
• You can write functions that return strings
• For example:

def get_name():
# Get the user’s name.
name = input(‘Enter your name:’)
# Return the name.
return name
Returning Boolean Values
• Boolean function: returns either True or False
– Use to test a condition such as for decision and
repetition structures
 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
• In Python, a function can return multiple values
– Specified after the return statement separated by
commas
 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
• The special value None means “no value”
• Sometimes it is useful to return None from a function
to indicate that an error has occurred

def divide(num1, num2):


if num2 == 0:
result = None
else:
result = num1 / num2
return result
Example: Sales Commission

• Example: Hal owns a business named Make Your


Own Music, which sells guitars, drums, banjos,
synthesizers, and many other musical instruments.
Hal’s sales staff works strictly on commission. At the
end of the month, each salesperson’s commission is
calculated according to Table shown below:
Sales Commission
• For example, a salesperson with $16,000 in monthly sales will earn a 14 percent commission
($2,240). Another salesperson with $18,000 in monthly sales will earn a 16 percent commission
($2,880). A person with $30,000 in sales will earn an 18 percent commission ($5,400). Because the
staff gets paid once per month, Hal allows each employee to take up to $2,000 per month in
advance. When sales commissions are calculated, the amount of each employee’s advanced pay is
subtracted from the commission. If any salesperson’s commissions are less than the amount of their
advance, they must reimburse Hal for the difference. To calculate a salesperson’s monthly pay, Hal
uses the following formula: Hal has asked you to write a program that makes this calculation for him.

• Algorithm/Pseudo code:
– 1. Get the salesperson's monthly sales.
– 2. Get the amount of advanced pay.
– 3. Use the amount of monthly sales to determine the commission rate.
– 4. Calculate the salesperson's pay using the formula above. If the amount is negative, indicate that the
salesperson must reimburse the company.

• Coding/Testing
The math Module (1 of 3)
• 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 (2 of 3)
Table 5-2 Many of the functions in the math module

math Module Function Description


acos(x) Returns the arc cosine of x, in radians.
asin(x) Returns the arc sine of x, in radians.
atan(x) Returns the arc tangent of x, in radians.
ceil(x) Returns the smallest integer that is greater than or equal to x.
cos(x) Returns the cosine of x in radians.
degrees(x) Assuming x is an angle in radians, the function returns the angle converted to
degrees.
exp(x) Returns ex
floor(x) Returns the largest integer that is less than or equal to x.
hypot(x, y) Returns the length of a hypotenuse that extends from (0, 0) to (x, y).
log(x) Returns the natural logarithm of x.
log10(x) Returns the base-10 logarithm of x.
radians(x) Assuming x is an angle in degrees, the function returns the angle converted to
radians.
sin(x) Returns the sine of x in radians.
sqrt(x) Returns the square root of x.
tan(x) Returns the tangent of x in radians.
The math Module (3 of 3)
• 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
• Variables must also be called using the dot notation
– Example:
circle_area = math.pi * radius**2
Storing Functions in Modules (1 of 2)
• In large, complex programs, it is important to keep
code organized
• Modularization: grouping related functions in modules
– Makes program easier to understand, test, and
maintain
– Make it easier to reuse code for multiple different
programs
 Import the module containing the required function to
each program that needs it
Storing Functions in Modules (2 of 2)
• Module is a file that contains Python code
– Contains function definition but does not contain calls
to the functions
 Importing programs will call the functions

• Rules for module names:


– File name should end in .py
– Cannot be the same as a Python keyword
• Import module using import statement
Menu Driven Programs
• 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
• Program uses a decision structure to determine the
selected menu option and required operation
– Typically repeats until the user quits
Conditionally Executing the main
Function (1 of 3)
• It is possible to create a module that can be run as a
standalone program or imported into another program

• Suppose Program A defines several functions that


you want to use in Program B

• So, you import Program A into Program B

• However, you do not want Program A to execute its


main function when you import it
Conditionally Executing the main
Function (2 of 3)
• In the aforementioned scenario, you write each
module so it executes its main function only when the
module is being run as the main program
– When a source code file is loaded into the Python
interpreter, a special variable called __name__ is created
– If the source code file has been imported as a module,
the __name__ variable will be set to the name of the
module.
– If the source code file is being executed as the main
program, the __name__ variable will be set to the value
'__main__'.
Conditionally Executing the main
Function (3 of 3)
• To prevent the main function from being executed
when the file is imported as a module, you can
conditionally execute main
def main():
statement
statement

def my_function():
statement
statement

if __name__ == '__main__':
main()
Turtle Graphics: Modularizing Code
with Functions (1 of 6)
• Commonly needed turtle graphics operations can be
stored in functions and then called whenever needed.
• For example, the following function draws a square.
The parameters specify the location, width, and color.
def square(x, y, width, color):
turtle.penup() # Raise the pen
turtle.goto(x, y) # Move to (X,Y)
turtle.fillcolor(color) # Set the fill color
turtle.pendown() # Lower the pen
turtle.begin_fill() # Start filling
for count in range(4): # Draw a square
turtle.forward(width)
turtle.left(90)
turtle.end_fill() # End filling
Turtle Graphics: Modularizing Code
with Functions (2 of 6)
• The following code calls the previously shown
square function to draw three squares:

square(100, 0, 50, 'red')


square(-150, -100, 200,
'blue')
square(-200, 150, 75, 'green')
Turtle Graphics: Modularizing Code
with Functions (3 of 6)
• The following function draws a circle. The parameters
specify the location, radius, and color.

def circle(x, y, radius, color):


turtle.penup() # Raise the pen
turtle.goto(x, y - radius) # Position the turtle
turtle.fillcolor(color) # Set the fill color
turtle.pendown() # Lower the pen
turtle.begin_fill() # Start filling
turtle.circle(radius) # Draw a circle
turtle.end_fill() # End filling
Turtle Graphics: Modularizing Code
with Functions (4 of 6)
• The following code calls the previously shown
circle function to draw three circles:

circle(0, 0, 100, 'red')


circle(-150, -75, 50, 'blue')
circle(-200, 150, 75, 'green')
Turtle Graphics: Modularizing Code
with Functions (5 of 6)
• The following function draws a line. The parameters
specify the starting and ending locations, and color.

def line(startX, startY, endX, endY, color):


turtle.penup() # Raise the pen
turtle.goto(startX, startY) # Move to the starting point
turtle.pendown() # Lower the pen
turtle.pencolor(color) # Set the pen color
turtle.goto(endX, endY) # Draw a square
Turtle Graphics: Modularizing Code
with Functions (6 of 6)
• The following code calls the previously shown line
function to draw a triangle:

TOP_X = 0
TOP_Y = 100
BASE_LEFT_X = -100
BASE_LEFT_Y = -100
BASE_RIGHT_X = 100
BASE_RIGHT_Y = -100
line(TOP_X, TOP_Y, BASE_LEFT_X, BASE_LEFT_Y, 'red')
line(TOP_X, TOP_Y, BASE_RIGHT_X, BASE_RIGHT_Y, 'blue')
line(BASE_LEFT_X, BASE_LEFT_Y, BASE_RIGHT_X, BASE_RIGHT_Y, 'green')
Summary (1 of 2)
• This topic 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 (2 of 2)
– Value-returning functions, including:
 Writing value-returning functions
 Using value-returning functions
 Functions returning multiple values
– Using library functions and the import statement
– Modules, including:
 The random and math modules
 Grouping your own functions in modules
– Modularizing Turtle Graphics Code

You might also like