Functions Joan Boone jpboone@email.unc.edu Summer 2020 Slide 1 - - PowerPoint PPT Presentation

functions
SMART_READER_LITE
LIVE PREVIEW

Functions Joan Boone jpboone@email.unc.edu Summer 2020 Slide 1 - - PowerPoint PPT Presentation

INLS 560 Programming for Information Professionals Functions Joan Boone jpboone@email.unc.edu Summer 2020 Slide 1 Topics Part 1 Overview of functions Part 2 Function arguments Part 3 Variable scope Part 4 Value-returning


slide-1
SLIDE 1

Slide 1

Functions

Joan Boone

jpboone@email.unc.edu

Summer 2020

INLS 560

Programming for Information Professionals

slide-2
SLIDE 2

Slide 2

Topics

Part 1

  • Overview of functions

Part 2

  • Function arguments

Part 3

  • Variable scope

Part 4

  • Value-returning functions
slide-3
SLIDE 3

Slide 3

Why Use Functions?

Simpler code

  • Easier to understand a program when it is broken down into

functions; “divide and conquer” approach

  • Easier to read than one long sequence of statements

Code reuse

  • Reduces the duplication of code and makes programs smaller
  • If a task is performed multiple times at different places in your

program, it can be written once and called when needed

  • Also, enables faster development across multiple programs

Easier to debug and test

  • By testing each function, it is easier to isolate and fix errors
  • Easier to maintain: only have to fix it once

Source: Starting Out with Python by Tony Gaddis

slide-4
SLIDE 4

Slide 4

Some Familiar Built-in Functions

print('Gross pay:', gross_pay) hours_worked = input('Enter hours worked: ') temp = float(temp) attendees = int(attendees) formatted_tax_value = format(tax, ',.2f') temp_is_a_number = temp.isnumeric()

slide-5
SLIDE 5

Slide 5

Use Functions for Basic Tasks

INPUT

hours_worked = 40 hourly_pay_rate = 25.00 gross_pay = hours_worked * hourly_pay_rate print(gross_pay)

1000.0

PROCESS OUTPUT

slide-6
SLIDE 6

Slide 6

Program Tasks: Input, Process, Output

  • Programs typically consist of many sub-tasks that handle input,

processing, and output

  • Recall the Gross Pay Calculator program:

hours_worked = float(input('Enter hours worked: '))

hourly_pay_rate = float(input('Enter hourly pay rate: ')) gross_pay = hours_worked * hourly_pay_rate print('Gross pay:', gross_pay)

  • The design for a more realistic version might look like:

Get hours worked

Get hourly pay rate

Calculate regular pay

Calculate overtime pay

Calculate deductions

Calculate net pay

Generate paycheck

slide-7
SLIDE 7

Slide 7

Use functions to 'divide and conquer' a large task

Source: Starting Out with Python by Tony Gaddis

Input task:

  • Get employee's hourly pay rate
  • Get number of hours worked

A function is a group of statements that performs a specific task

Process task:

  • Calculate regular pay
  • Calculate overtime pay

Process task:

  • Calculate deductions
  • Calculate net pay

Output task:

  • Generate paycheck
slide-8
SLIDE 8

Slide 8

2 Types of Functions

Function that returns a value

  • Executes the statements it contains and returns a value back

to the statement where it was called

  • Examples:

hours_worked = input('Enter hours worked: ') temp = float(temp) price = int(price)

Void function (no value returned)

  • Executes the statements it contains and then returns back to

the statement where it was called. Void functions do not return any values.

  • Example: print('Gross pay:', gross_pay)
slide-9
SLIDE 9

Slide 9

Defining Functions

General format

def function_name(): statement statement etc.

Function naming rules

– Don't use Python keywords – Should be lowercase (snake_case or camelCase) – Case-sensitive: upper and lowercase characters are distinct – Should be descriptive; often in verb form, e.g., get_input(),

calculate_cost(), display_results()

Example

def display_message(): print('Life is like riding a bicycle.') print('To keep your balance, you must keep moving.')

slide-10
SLIDE 10

Slide 10

Defining and Calling Functions

# Define a function named display_message def display_message(): print('Life is like riding a bicycle.') print('To keep your balance, you must keep moving.') # Call the message function display_message()

These statements define the display_message function so that it can be called by other statements in your program. This statement calls the display_message function, causing it to be executed. IMPORTANT: the function must be defined before it can be called.

function_demo.py

slide-11
SLIDE 11

Slide 11

Programs with Multiple Functions

  • You can define many functions in a program
  • It is common to have a main function that calls other functions in a

program as needed

  • The main function typically contains the 'mainline' or overall logic of

a program

# Define the main function def main(): print ('A quote from Albert Einstein:') display_message() print('...in a letter to his son, 1930') # Define the message function def display_message(): print('\tLife is like riding a bicycle.') print('\tTo keep your balance, you must keep moving.') # Call the main function

main()

two_functions.py

slide-12
SLIDE 12

Slide 12

Flow of Function Execution

# This program has 2 functions # Define the main function def main(): print ('A quote from Albert Einstein:') display_message() print('...in a letter to his son, 1930') # Define the display_message function def display_message(): print('\tLife is like riding a bicycle.') print('\tTo keep your balance, you must keep moving.') # Call the main function main() 1 2 3 4

  • 1. main function is called, so the interpreter jumps to the main function and begins

executing its statements

  • 2. display_message function is called, and its statements are executed
  • 3. When finished, the interpreter jumps back to where the display_message

function was called and resumes executing there

  • 4. When main is finished, jump back to where it was called, and the program ends
slide-13
SLIDE 13

Slide 13

Payroll Program with Multiple Functions

Payroll program steps

  • Get hours worked
  • Get hourly pay rate
  • Calculate regular pay
  • Calculate overtime pay
  • Calculate deductions
  • Calculate net pay
  • Generate paycheck

def main(): get_input() calculate_gross_pay() calculate_deductions() calculate_net_pay() generate_paycheck() def get_input(): # get hours_worked # get hourly_pay_rate def calculate_gross_pay(): # calculate regular_pay # calculate overtime_pay # gross_pay = regular_pay + overtime_pay def calculate_deductions(): # calculate taxes # calculate benefits # deductions = taxes + benefits def calculate_net_pay(): # net_pay = gross_pay - deductions def generate_paycheck(): # print paycheck or direct deposit main()

slide-14
SLIDE 14

Slide 14

Topics

Part 1

  • Overview of functions

Part 2

  • Function arguments

Part 3

  • Variable scope

Part 4

  • Value-returning functions
slide-15
SLIDE 15

Slide 15

Passing Arguments to Built-in Functions

  • Functions are often defined so that they can accept an

argument – this allows the function to perform the same task, but with different data

  • An argument is any piece of data that can be passed into a

function when a function is called

  • Examples of built-in Python functions with arguments:

print('Gross pay:', gross_pay) hours_worked = input('Enter hours worked: ') temp = float(temp) price = int(price) formatted_tax_value = format(tax, ',.2f')

Source: Starting Out with Python by Tony Gaddis

slide-16
SLIDE 16

Slide 16

Function Arguments and Parameters

  • You can call a function, show_double, with an argument, some_number
  • In the function definition, the variable that receives the argument, number,

is called a parameter

Source: Starting Out with Python by Tony Gaddis

# This program demonstrates an argument being # passed to a function def main(): some_number = 5 show_double(some_number) # 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() some_number is a variable passed as an argument number is a parameter variable

The value of the some_number variable is copied to the number variable, so both variables have a value of 5

pass_arg.py

slide-17
SLIDE 17

Slide 17

Another Example of Passing an Argument to a Function

Design

  • Display an introduction of

what the program does

  • Get the number of cups
  • Convert cups to ounces and

display results

Source: Starting Out with Python by Tony Gaddis # Convert cups to fluid ounces def main (): display_intro() # display the intro info cups_needed = int(input('Enter the number of cups: ')) # Get cups convert_cups_to_ounces(cups_needed) # Convert cups to ounces def display_intro(): print('This program converts measurements in cups to fluid ounces') print(' 1 cup = 8 fluid ounces') def convert_cups_to_ounces(cups): # cups is the value entered by user

  • unces = cups * 8

print(cups, 'cups converts to', ounces, 'ounces.') main()

Hierarchy chart

main() intro() cups_to_ounces(cups)

cups_to_ounces.py

slide-18
SLIDE 18

Slide 18

Built-in Functions with Multiple Arguments

print('Gross pay:', gross_pay) string label calculated result formatted_tax = format(tax, ',.2f') string with format specification random_number = random.randint(1, 52)

Source: Starting Out with Python by Tony Gaddis

value to format lower bound upper bound

slide-19
SLIDE 19

Slide 19

Functions with Multiple Arguments

Arguments are passed by position to the corresponding parameter variables in the function. This means

  • first argument is passed to the first parameter variable
  • second argument is passed to the second parameter variable

def main(): print('Sum of 12 and 45 is') show_sum(12, 45) def show_sum(num1, num2): result = num1 + num2 print(result) main() def main(): first_name = input('Enter your first name: ') last_name = input('Enter your last name: ') print('Your name reversed is') reverse_name(first_name, last_name) def reverse_name(first, last): print(last, first) main()

Called a parameter list, where variables are separated by commas

Source: Starting Out with Python by Tony Gaddis

slide-20
SLIDE 20

Slide 20

Functions with Multiple Arguments

  • The Math Quiz example generate 2 random numbers, prompts the user

for the sum, and displays a message indicating the result.

  • The example has functions that accept multiple arguments, and one

function that returns a value.

def main(): # Get numbers num1 = random.randint(0, 999) num2 = random.randint(0, 999) # Display math problem displayProblem(num1, num2) # Get user answer userAnswer = getAnswer() # Calculate correct answer correctAnswer = num1 + num2 # Display result showResult(correctAnswer, userAnswer)

258 + 400 Enter sum of numbers: 658 Correct answer, good Work! Source: Starting Out with Python by Tony Gaddis

math_quiz.py

110 + 428 Enter sum of numbers: 528 Incorrect... The correct answer is: 538

Results

slide-21
SLIDE 21

Slide 21

Standard Library Functions and the import statement

Python functions

  • Some of the Python functions are part of the Python interpreter. If you

want to use them, you just the call the function. Examples are print,

input, range

  • Other functions are stored in modules. To call these functions, you

first must include an import statement at the top of your program

– Examples: import math, import random – These statements cause the interpreter to load the contents of a

module, and make all of its functions available to your program

Math functions: ceil and floor

  • ceil returns the smallest integer >= the argument (rounds up)
  • floor returns the largest integer <= the argument (rounds down)
  • math.ceil(4.7) → 5 math.floor(4.7) → 4
  • math.ceil(8.2) → 9 math.floor(8.2) → 8
slide-22
SLIDE 22

Slide 22

Exercise: Paint Job Estimator

  • For every 400 square feet of wall space, 1 gallon of paint and 5 hours
  • f labor are required. The painter charges $35/hour
  • Define 2 functions: main and show_cost_estimate

– main function

Initializes the fixed values, for example:

Prompts for wall space in square feet, and the price of a gallon of paint

Determine number of gallons of paint needed

Calculates labor hours, labor cost, and paint cost

Calls show_cost_estimate function to calculate the total cost and display the results

  • Sample input and output:

Enter wall space in square feet: 540 Enter paint price per gallon: 35 Gallons of paint: 2 Hours of labor: 10 Paint charges: $70.00 Labor charges: $350.00 Total cost: $420.00

feet_per_gallon = 400 labor_hours = 5 labor_charge = 35

paint_job_estimator.py

slide-23
SLIDE 23

Slide 23

Topics

Part 1

  • Overview of functions

Part 2

  • Function arguments

Part 3

  • Variable scope

Part 4

  • Value-returning functions
slide-24
SLIDE 24

Slide 24

Local Variables

  • So far, the variables you have defined in a program have been

accessible to all statements in the program

  • A variable defined inside a function is considered a local variable

– Local variables cannot be accessed outside of the function – Local variables are only known within the function they are defined in

# Definition of the main function def main(): get_name() print('Hello', name) # Definition of the get_name function def get_name(): name = input('Enter your name: ') # Call the main function main()

Source: Starting Out with Python by Tony Gaddis

slide-25
SLIDE 25

Slide 25

Scope and Local Variables

  • A variable's scope is the part of a program where the variable can be

accessed

  • A variable is visible only to statements in its scope
  • A local variable's scope is the function in which the variable is created
  • Because a function's local variables are hidden from other functions, the
  • ther functions may have variables with the same name, but they

represent different variables

def main(): texas() california() def texas(): birds = 5000 print('texas has', birds, 'birds') def california(): birds = 8000 print('california has', birds, 'birds') main() Source: Starting Out with Python by Tony Gaddis

Output

texas has 5000 birds california has 8000 birds

slide-26
SLIDE 26

Slide 26

Scope of Parameter Variables

  • The scope of a parameter variable is the function in which it is used
  • Like a local variable, all of the statements inside the function can access

the parameter variable, but no statement outside of the function can access it.

Making changes to parameters

  • Any change made to the value of a parameter variable in a function

does not affect the value of the corresponding argument

Source: Starting Out with Python by Tony Gaddis

def main(): number = 99 print('The value is', number) change_me(number) print('Back in main, value is', number) def change_me(parm): print('I am changing the value') parm = 0 print('Now the value is', parm) main()

Output

The value is 99 I am changing the value Now the value is 0 Back in main, value is ??

slide-27
SLIDE 27

Slide 27

Global Variables

  • When a variable is created by an

assignment statement outside all of the functions in a program, the variable is global in scope

  • A global variable is accessible to all
  • f the functions in a program

# Create a global variable my_value = 10 def show_value(): print(my_value) show_value() # Create a global variable number = 0 def main(): global number number = int(input('Enter a number: ')) show_number() def show_number(): print('Number entered is', number) main()

  • If you want to

change the value of a global variable in a function, you have to declare the variable as global in the function

Source: Starting Out with Python by Tony Gaddis

slide-28
SLIDE 28

Slide 28

More on Global Variables

Recommendation: restrict the use of global variables

  • Can make debugging difficult. In very large programs, if many functions

can change the value of a global variable and it is assigned a bad value, it can be hard to find the culprit.

  • If you want to reuse a function in another program but it is dependent on

a global variable, then you may have to modify the function.

  • Can make a program hard to understand. You have to understand all of

the places that a global variable is used and modified.

Alternative

  • If a variable is used by a few functions, then consider passing it as a

parameter to each function that needs it. Keeping data “close” to the functions that use it can make a program easier to understand.

When global variables are a good approach

  • If a variable is used by many functions, then it might be a good

candidate to be defined as a global variable.

slide-29
SLIDE 29

Slide 29

Topics

Part 1

  • Overview of functions

Part 2

  • Function arguments

Part 3

  • Variable scope

Part 4

  • Value-returning functions
slide-30
SLIDE 30

Slide 30

Value-Returning Built-in Functions

Statement Returns a value

  • f type

hours_worked = input('Enter hours worked: ') string temp = float(temp) float number price = int(price) integer number formatted_tax = format(tax, ',.2f') string random_number = random.randint(0, 2) integer temp_is_a_number = temp.isnumeric() boolean

Python Standard Library Functions

  • Many are built into the Python interpreter, and you simply call the function
  • Others require an import statement that tells the interpreter the name of

the module that contains the function For example, you need to include import random to use the randint function, and import math to use the ceil function

slide-31
SLIDE 31

Slide 31

Writing value-returning functions

A value-returning function has a return statement that returns a value back to the statement that called it.

General format

def function_name():

statement statement etc. return expression

Simple example

def sum(num1, num2):

result = num1 + num2 return result # This program defines a sum function that returns a value def main(): first_age = int(input('Enter your age: ')) second_age = int(input("Enter a friend's age: ")) total = sum(first_age, second_age) print('Together you are', total, 'years old') def sum(num1, num2): result = num1 + num2 return result main()

Source: Starting Out with Python by Tony Gaddis

slide-32
SLIDE 32

Slide 32

Math Quiz: displayProblem(num1, num1) is a value-returning function

def main(): # Get numbers num1 = random.randint(0, 999) num2 = random.randint(0, 999) # Display math problem userAnswer = displayProblem(num1, num2) # Calculate correct answer correctAnswer = num1 + num2 # Display result showResult(correctAnswer, userAnswer) # Accepts the numbers and displays them def displayProblem(num1, num2): print(format(num1, '5')) print('+', end='') print(format(num2, '4')) inputAnswer = int(input('Enter sum of numbers: ')) return inputAnswer math_quiz_v2.py Function returns a value Assign the value to a variable so you can use it in this function Call a function to get some value

1 2 3

slide-33
SLIDE 33

Slide 33

Returning Multiple Values from a Function

  • Many value-returning functions only return a single value
  • Python allows you to return multiple values, separated by commas
  • When you call a function that returns multiple values, you need to

define multiple values on the left side of the assignment statement

  • Exercise: modify math_quiz_v2.py to include a new function,

getNumbers() that returns multiple values that correspond to num1 and num2

def main(): # Get numbers num1, num2 = getNumbers()

...