0% found this document useful (0 votes)
3 views49 pages

Python Functions

The document provides an overview of Python programming with a focus on writing functions, including defining, calling, and the benefits of modularizing code. It covers void and value-returning functions, local and global variables, and the use of libraries and modules for generating random numbers. Additionally, it discusses the importance of function design, including using IPO charts and returning multiple values.

Uploaded by

aidankoh6
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)
3 views49 pages

Python Functions

The document provides an overview of Python programming with a focus on writing functions, including defining, calling, and the benefits of modularizing code. It covers void and value-returning functions, local and global variables, and the use of libraries and modules for generating random numbers. Additionally, it discusses the importance of function design, including using IPO charts and returning multiple values.

Uploaded by

aidankoh6
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/ 49

PYTHON PROGRAMMING

WRITING FUNCTIONS
TOPICS

•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 (CONT’D.)

• Introduction to Value-Returning Functions:


Generating Random Numbers
• Writing Your Own Value-Returning Functions
• The math Module
• 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
• 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
 Functions are given names
 Function naming rules:
 Cannot use key words 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 (CONT’D.)
 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 (CONT’D.)
 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 (CONT’D.)
 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 (CONT’D.)
• 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
•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 (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.)
LOCAL VARIABLES

• 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 (CONT’D.)

• 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
• 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 (CONT’D.)
PASSING ARGUMENTS TO
FUNCTIONS (CONT’D.)
• 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 (CONT’D.)
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.
PASSING MULTIPLE
ARGUMENTS (CONT’D.)
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

• 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)
• Possible to mix keyword and positional arguments
when calling a function
 Positional arguments must appear first
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
• General format: global variable_name
GLOBAL VARIABLES AND
GLOBAL CONSTANTS
(CONT’D.)
• 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
• 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
STANDARD LIBRARY FUNCTIONS
AND THE IMPORT STATEMENT
(CONT’D.)
•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
(CONT’D.)
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.)
• 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.)
GENERATING RANDOM
NUMBERS (CONT’D.)
GENERATING RANDOM
NUMBERS (CONT’D.)
• 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
WRITING YOUR OWN VALUE-
RETURNING FUNCTIONS
• 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
(CONT’D.)
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

• 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 (CONT’D.)
RETURNING STRINGS

• You can write functions that return strings


• For example:
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

You might also like