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

Functions

Uploaded by

minaergec2004
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Functions

Uploaded by

minaergec2004
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

Functions

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5-1


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5-2


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5-3


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5-4


Introduction to Functions (2 of 2)

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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5-5


Introduction to Functions
• Modularized program: program wherein each
task within the program is in its own function

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5-6


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5-7


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.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5-8


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
 Allother characters must be a letter, number
or underscore
 Uppercase and lowercase characters are
distinct

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5-9


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 10


Example
# This program demonstrates a function.
# First, we define a function named
message.
def message():
print('I am Arthur,')
print('King of the Britons.')

# Call the message function.


message()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 11


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 12


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 13


Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 14
Defining and Calling a
Function (5 of 5)
 In fact, it is common for a program to
have a main function.

• main function: called when the program


starts
 Calls other functions when they are
needed
 Defines the mainline logic of the program

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 15


Example
# This program has two functions. First we
# define the main function.
def main():
print('I have a message for you.')
message()
print('Goodbye!')
# Next we define the message function.
def message():
print('I am Arthur,')
print('King of the Britons.')
# Call the main function.
main()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 16


Indentation in Python

• Each block must be indented


 Lines in block must begin with the same
number of spaces
 Usetabs 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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 17


Designing a Program to Use
Functions (1 of 4)
• 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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 18


Designing a Program to Use
Functions (2 of 4)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 19


Designing a Program to Use
Functions (3 of 4)
• 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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 20


Designing a Program to Use Functions
(4 of 4)

Figure 5-10 : A hierarchy chart

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 21


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 22


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 23


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 24


Example
# Definition of the main function.
def main():
get_name()
print(f'Hello {name}.') # This causes an
error!
# Definition of the get_name function.
def get_name():
name = input('Enter your name: ')

# Call the main function.


main()

 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.
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 25
Example
# This program demonstrates two functions that have local variables with
the same name.
def main(): # Call the texas function.
texas() # Call the california function.
california() # Definition of the texas function. It creates a local
variable named birds.
def texas():
birds = 5000
print(f'texas has {birds} birds.')
# Definition of the california function. It also
# creates a local variable named birds.
def california():
birds = 8000
print(f'california has {birds} birds.')
# Call the main function. main()
main()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 26


Passing Arguments to
Functions (1 of 4)
• Argument: piece of data that is sent
into a function
 Function can use argument in
calculations or other operations
 When calling the function, the
argument is placed in parentheses
following the function name

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 27


Passing Arguments to Functions (2 of 4)

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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 28


Example

# This program demonstrates an argument being


# passed to a function.
def main():
value = 5
show_double(value)

# The show_double function accepts an argument


# and displays double its value.
def show_double(number):
result = number * 2
print(result)
# Call the main function.
main()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 29


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
 All of the statements inside the function can access the
parameter variable, but no statement outside the
function can access it.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 30


Passing Arguments to Functions (4 of 4)

Figure 5-14 The value variable and the number parameter reference the same value

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 31


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.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 32


Passing Multiple Arguments (2 of 2)

Figure 5-16 Two arguments passed to two parameters

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 33


Example
# This program demonstrates a function that accepts
# two arguments.
def main():
print('The sum of 12 and 45 is')
show_sum(12, 45)

# The show_sum function accepts two arguments


# and displays their sum.
def show_sum(num1, num2):
result = num1 + num2
print(result)

# Call the main function.


main()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 34


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
 Callingfunction can communicate with
called function

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 35


Making Changes to Parameters (2 of 3)

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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 36


Example
# This program demonstrates what happens when you
# change the value of a parameter.
def main():
value = 99
print(f'The value is {value}.')
change_me(value)
print(f'Back in main the value is {value}.')

def change_me(arg):
print('I am changing the value.')
arg = 0
print(f'Now the value is {arg}.')

# Call the main function.


main()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 37


Making Changes to
Parameters (3 of 3)

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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 38


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 39


Example
# This program demonstrates keyword arguments.
def main():
# Show the amount of simple interest, using 0.01 as
# interest rate per period, 10 as the number of periods,
# and $10,000 as the principal.
show_interest(rate=0.01, periods=10, principal=10000.0)
# The show_interest function displays the amount of
# simple interest for a given principal, interest rate
# per period, and number of periods.
def show_interest(principal, rate, periods):
interest = principal * rate * periods
print(f'The simple interest will be ${interest:,.2f}.')
# Call the main function.
main()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 40


Example

# This program demonstrates passing two strings as


# keyword arguments to a function.
def main():
first_name = input('Enter your first name: ')
last_name = input('Enter your last name: ')
print('Your name reversed is')
reverse_name(last=last_name, first=first_name)
def reverse_name(first, last):
print(last, first)
# Call the main function.
main()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 41


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
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 42
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
 Makesfunction hard to transfer to another
program
 Global variables make a program hard to
understand

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 43


Example

# Create a global variable.


my_value = 10
# The show_value function prints
# the value of the global variable.
def show_value():
print(my_value)
# Call the show_value function.
show_value()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 44


Example
# Create a global variable.
number = 0
def main():
global number
number = int(input('Enter a number: '))
show_number()
def show_number():
print(f'The number you entered is {number}.')
# Call the main function.
main()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 45


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 46


Example

 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.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 47


Code of Example

# The following is used as a global constant to represent


# the contribution rate.
CONTRIBUTION_RATE = 0.05
def main():
gross_pay = float(input('Enter the gross pay: '))
bonus = float(input('Enter the amount of bonuses: '))
show_pay_contrib(gross_pay)
show_bonus_contrib(bonus)
# The show_pay_contrib function accepts the gross
# pay as an argument and displays the retirement
# contribution for that amount of pay.
def show_pay_contrib(gross):
contrib = gross * CONTRIBUTION_RATE
print(f'Contribution for gross pay: ${contrib:,.2f}.')
# The show_bonus_contrib function accepts the
# bonus amount as an argument and displays the
# retirement contribution for that amount of pay.
def show_bonus_contrib(bonus):
contrib = bonus * CONTRIBUTION_RATE
print(f'Contribution for bonuses: ${contrib:,.2f}.')
# Call the main function.
main()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 48


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
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 49
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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 50


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 51


Standard Library Functions and the
import Statement (3 of 3)
• Because you do not see the internal workings of library
functions, many programmers think of them as black boxes.

• The term “black box” is used to describe any mechanism that


accepts input, performs some operation (that cannot be seen)
using the input, and produces output.

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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 52


Generating Random Numbers (1 of 5)
• Random numbers are useful in a lot of
programming tasks:
• Random numbers are commonly used in games.
• Random numbers are useful in simulation
programs.
• Random numbers are useful in statistical programs
that must randomly select data for analysis.
• Random numbers are commonly used in
computer security to encrypt sensitive data.
• 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()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 53


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 (terminal)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 54


Generating Random Numbers (3 of 5)

Figure 5-20 A statement that calls the random function

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 55


Generating Random Numbers (4 of 5)

Figure 5-21 The random function returns a value

Figure 5-22 Displaying a random number

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 56


Example

# This program displays a random number


# in the range of 1 through 10.
import random
def main():
# Get a random number.
number = random.randint(1, 10)
# Display the number.
print(f'The number is {number}.')
# Call the main function.
main()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 57


Example

# This program displays five random


# numbers in the range of 1 through 100.
import random
def main():
for count in range(5):
# Get a random number.
number = random.randint(1, 100)
# Display the number.
print(number)
# Call the main function.
main()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 58


Example

# We can directly use the function in place-holder.


import random
print(f'The number is {random.randint(1, 100)}.')

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 59


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 60


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
 Bydefault uses system time for seed
 Can use random.seed() function to specify
desired seed value

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 61


Example
# This program displays same five random
# numbers in the range of 1 through 100.
import random
def main():
random.seed(10)
for count in range(5):
# Get a random number.
number = random.randint(1,100)
# Display the number.
print(number)
# Call the main function.
main()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 62


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
 Thevalue 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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 63


Writing Your Own Value-Returning
Functions (2 of 2)

Figure 5-23 Parts of the function

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 64


Example

# This program uses the return value of a function.


def main():
# Get the user's age.
first_age = int(input('Enter your age: '))
# Get the user's best friend's age.
second_age = int(input("Enter your best friend's
age: "))
# Get the sum of both ages.
total = sum(first_age, second_age)
# Display the total age.
print(f'Together you are {total} years old.')
# The sum function accepts two numeric arguments and
# returns the sum of those arguments.
def sum(num1, num2):
result = num1 + num2
return result
# Call the main function.
main()
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 65
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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 66


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
 Oftenincludes enough information to be
used instead of a flowchart

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 67


Using IPO Charts (2 of 2)

Figure 5-25 IPO charts for the getRegularPrice and discount functions

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 68


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 69


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 70


Example

def is_even(number):
# Determine whether number is even. If it is, set status
to true. Otherwise, set status to false.
if (number % 2) == 0:
status = True
else:
status = False
# Return the value of the status variable.
return status
number = int(input('Enter a number: '))
if is_even(number):
print('The number is even.')
else:
print('The number is odd.')

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 71


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 72


Example

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 73


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 74


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 75


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
Copyright © 2022 the tangent
Pearson of x in radians.
Education, Ltd. All Rights Reserved. 5 - 76
Example

# This program demonstrates the sqrt function.


import math
def main():
# Get a number.
number = float(input('Enter a number: '))
# Get the square root of the number.
square_root = math.sqrt(number)
# Display the square root.
print(f'The square root of {number} is
{square_root}.')
# Call the main function.
main()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 77


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 78


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
 Importthe module containing the required
function to each program that needs it

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 79


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 80


Summary (1 of 2)

• 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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 81


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 5 - 82

You might also like