Chapter 5: Functions

¡Supera tus tareas y exámenes ahora con Quizwiz!

Argument

- Function can use the argument in calculations. - When calling the function, the argument is placed in parentheses following the function name. Ex. pass_arg.py # This program demonstrates an argument being # passed to a function. def main(): value = 5 show_double(value) # The short_double functions accepts an argument and displays double its value. def show_double(number): result = number * 2 print(result) # Call the main function. main() >>> 10

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 - Introduction to Value-Returning Functions: Generating Random Numbers - Writing Your Own Value-Returning Functions - Writing Your Own Value-Reting Functions - The math Module - Storing Functions in Modules

Module

A file that contains Python code. - Contains the function definition but does not contain calls to the functions. - Importing programs will call the functions.

Value-Returning Function

A function that 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.

Void Function

A function that simply executes the statements it contains and then terminates.

Global Constants

A global name that references a value that cannot be changed. - It is permissible to use global constants in a program. - To simulate a global constant in Python, create a global variable and do not re-declare it within functions. Ex. retirement.py # 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 the amount of pay. def show_pay_contrib(gross_pay): contrib = gross_pay * CONTRIBUTION_RATE print('Contribution for gross pay: $', \ format(contrib, ',.2f'), \ sep='') # 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('Contribution for bonuses: $', \ format(contrib, ',.2f'), sep='') # Call the main function. main()

Void Function 2

A group of statements within a program performing a specific task. - Calls the function when you need to perform a task. - Returns None, a special return value that is essentially disregarded and not important. The task the function carries out it important.

Function

A group of statements within a program that perform a specific task. - Usually one task of a large program. - Functions can be executed in order to perform overall program task. - Known as the 'divide and conquer' approach.

Modularized Program

A program wherein each task within the program is in its own function.

Block

A set of statements that belong together as a group. - Ex. That statements included in a function.

Top-down Design

A technique for breaking algorithm into functions

Global Variables

A variable created by an assignment statement written outside all functions. - Can be accessed by any statement in the program file, including within a function. - If a function needs to assign a value to the global variable, the variable must be declared within the function. - General format: global variable_name Ex. global1.py # 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() Ex. global2.py # Create a global variable. number = 0 def main(): global number # Notice how number is defined in a function that calls other functions. number = int(input('Enter a number: ')) show_number() def show_number(): print('The number you entered is', number) # Call the main function. main():

Local Variable

A 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 function in which the local variable is created. 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. Ex. birds.py

Parameter variable

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

Keyword Argument

Argument that specifies which parameter the value should be passed to. - The position in calling function is irrelevant. - General Format: function_name(parameter = value) It is possible to mix keyword and positional arguments when calling a function. - Positional arguments must appear first. Ex. keyword_args.py # 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, principle=10000.0) # The show_interest function displays the amount # 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('The simple interest will be $, \ format(interest, ',.2f'), \ sep='') # Call the main function. main() 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 you 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()

Passing Arguments to Functions

Argument... Parameter variable... - Scope of a parameter...

Returning Boolean Values

Boolean function...

Making Changes to Parameters

Changes made to a parameter value within the function do not affect the argument. - Known as the "pass by value." - Provides a way for unidirectional communication between one function and another function. - Calling function can communicate with called function. Ex. change_me.py The value variable pass to the change_me function cannot be change by it.

Hierarchy Chart

Depicts the relationship between functions. A.K.A 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 of a function.

IPO Chart

Describes the input, processing, and output of a function (hence IPO). - Tool for designing and documenting functions. - Typically laid out in columns. - Usually provide a brief description of input, processing and output, without going into details. - Often includes enough information to be used instead of a flowchart.

Menu-drive Program

Displays a list of operations on the screen, allowing the user to select the desired operation. - A list of operations displays on the screen is called a menu. The program uses a decision structure to determine the selected menu option and required operation.

Indentation in Python

Each block must be indented. - The lines in the 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. Note: Observe Figure 5-7 All of the statements in a block are indented

Modules

Files that store functions of the standard library. - Helps organize library functions not built into the interpreter. - Copied to the computer when you install python. ***To call a function stored in a module, you need to write an import statement: - Written at the top of the program. - Format: import module_name Input >>> Library Function (Black Box) >>> Output

Defining and Calling a Function

Functions are given names. Function naming rules: - Cannot use keywords as a function name. - Cannot contain spaces. - First character must be a letter or an underscore. - All other characters must be a letter, number, or an underscore. - Uppercase and lowercase characters are distinct (case sensitive). The function name should be descriptive of the task carried out by the function. - Often includes a verb. Function definition... Function header... Block... You call a function to execute it: - When a function is called: - The interpreter jumps to the function and executes the statements in the block. - Then, the interpreter jumps back to the part of the program that called the function. - This is known as a "function return." main function...

randint Function

Generates a random number in the range provided by the arguments. - Returns the random number to part of the 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. randrange function... random function... uniform function...

Reasons to Avoid Using Global Variables

Global variables make debugging difficult: - There would be many locations in the code that could be causing a wrong variable value. Functions that use global variables are usually dependent on the global variable. - Makes the function hard to transfer to another program. Global variables make a program harder to understand.

Modularization

Grouping related functions in modules. In large, complex programs, it is important to keep code organized. - Makes the program easier to understand, test, and maintain. - Make it easier to reuse code for multiple different programs. - Import the module containing containing the required function to each program that needs it.

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 a function in an assignment statement, you need a separate variable on the left sift of the = operator to receive each returned value: def get_name(): # Get the user's first and last names. first = input('Enter you first name: ') last = input('Enter your last name: ') # Return both names. return first, last first_name, last_name = get_name()

Designing a Program to Use Functions

In a flowchart, the function call is shown as a rectangle with vertical bars at each side. - The function name is written in the symbol. - Typically draw separate flow chart for each function in the program. - End terminal symbol usually reads Return Top-down design... Hierarchy chart... Use the input function to have a program wait for the user to press enter.

random Module

Includes library functions for working with 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, it uses system time for seed. - Can use random.seed() function to specify the desired seed value.

Returning Boolean Values Example: Simplify Validation Code

Instead of this: # Get the model number. model = int(input('Enter the model number: ')) # Validate the model number. while model != 100 and model != 200 and model != 300: print('The value model numbers are 100, 200 and 300.') model = int(input('Enter a valid model number: ')) Do this: # Valide the model number. while is_invalid(model): print('The valid model numbers are 100, 200 and 300.') model = int(input('Enter a valid model number: ')) def is_invalid(mod_num): if mod_num != 100 and mod_num != 200 and mod_num != 300: status = True else: status = False return status

Dot Notation

Notation for calling a function belonging to a module. Format: module_name.function_name()

math Module

Part of the 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. Ex. square_root.py 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('The square root of', number, 'is', square_root) # Call the main function. main() 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: circle_area = math.pi * radius**2

Passing Multiple Arguments

Python allows writing a function that accepts multiple arguments. - The parameter list replaces a single parameter. - Parameter list items are separated by a comma. Arguments are passed BY POSITION to corresponding parameters. - The first parameter receives the value of the first argument, the second parameter receives the value of the second argument, etc. Ex. multiple_args.py # 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() >>> The sum of 12 and 45 is 57

Generating Random Numbers

Random numbers are useful in a lot of programming tasks! random module... Dot notation... randint function...

Random Number Seeds

Random numbers created by functions in the random module are actually only pseudo_random. Pseudo_random means somewhat random. Nothing is actually truly random. Seed value...

uniform function

Returns a random float but allows the user to specify the range. Ex. number = random.uniform(1.0, 10.0)

random Function

Returns a random float in the range of 0.0 and 1.0. Does not receive arguments.

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. Ex: def is_invalid(num): if mod_num != 100 and mod_num != 200 and mod_num != 300 else: status = False return status

randrange Function

Similar to range function, but returns a randomly selected integer from the resulting sequence. - Same arguments as the range function.

Value-returning Function 2

Similar to the void function, but it returns a value. - The value is return to the part of the program that called the function when the function finishes executing. - The task that the function carries out is important AND the return value is important.

Function Definition

Specifies what the function does. 'def' in code. def function_name(): statement statement

The Benefits of Modularizing a Program with Functions

The benefits of using functions include: - Simpler code: - Functions sensibly divide the code instead of one giant chunk. - Function call looks cleaner and gives a relationship between different lines of code. - Code reuse: - Write the code on and call it multiple times. - Better testing and debugging: - Can test and debug each function individually. - Faster development for common tasks: - Functions can be written for tasks common among a team instead of each programmer creating their own version of the function. - Easier facilitation for teamwork: - Different team members can write different functions. - Better distribution of work.

Rules for Module Names

The file name should end in .py Cannot be the same as a Python keyword. Import a module using the import statement.

Function Header

The first line of a function. - Includes keyword def and function name, followed by parentheses and a colon.

main Function

The function called when the program starts. - Calls other functions when they are needed. - Defines the "mainline logic" of the program. Note: Observe Figure 5-3 Calling the main function Observe Figure 5-4 Calling the message function Observe Figure 5-5 The message function returns Observe Figure 5-6 The main function returns

Standard Library

The library of pre-written functions that comes with Python. - Library functions perform tasks that programmers commonly need. - Ex. print, input, range. - Viewed by programmers as a "black box". Some library functions are built into the Python interpreter. - To use, just call the function.

Scope

The part of a program in which a variable may be accessed. - For local variables: the scope will be function in which it is created.

Writing You Own Value Returning Functions

To write a value-returning function, you need to write a simple function and add one or more return statements. - Format: return expression - 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. Ex. total_ages.py # 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('Together you are', total, 'years old.') # The sum function accepts two numeric arguments and # returns the same of those arguments. def sum(num1, num2): result = num1 + num2 return result # Call the main function.

How to Use Value-Returning Functions

Value-returning functions can be useful in specific situations: - ex. 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.

Returning Strings

You can write functions that return strings. Ex: def get_name(): # Get the user's name. name = input('Enter your name: ') # Return the name. return name


Conjuntos de estudio relacionados

UIL Social Studies 2023-2024: Individuals

View Set

Clinical Level Final Mock Exam II

View Set

Health and Life (chapters 8 & 9)

View Set