Slide 1
Functions
Joan Boone
jpboone@email.unc.edu
Summer 2020
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
Joan Boone
jpboone@email.unc.edu
Summer 2020
Slide 2
Slide 3
Simpler code
functions; “divide and conquer” approach
Code reuse
program, it can be written once and called when needed
Easier to debug and test
Source: Starting Out with Python by Tony Gaddis
Slide 4
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
hours_worked = 40 hourly_pay_rate = 25.00 gross_pay = hours_worked * hourly_pay_rate print(gross_pay)
1000.0
Slide 6
processing, and output
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)
–
Get hours worked
–
Get hourly pay rate
–
Calculate regular pay
–
Calculate overtime pay
–
Calculate deductions
–
Calculate net pay
–
Generate paycheck
Slide 7
Source: Starting Out with Python by Tony Gaddis
Input task:
A function is a group of statements that performs a specific task
Process task:
Process task:
Output task:
Slide 8
to the statement where it was called
hours_worked = input('Enter hours worked: ') temp = float(temp) price = int(price)
the statement where it was called. Void functions do not return any values.
Slide 9
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
# 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
program as needed
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
# 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
executing its statements
function was called and resumes executing there
Slide 13
Payroll program steps
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 15
argument – this allows the function to perform the same task, but with different data
function when a function is called
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
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
Design
what the program does
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
print(cups, 'cups converts to', ounces, 'ounces.') main()
Hierarchy chart
main() intro() cups_to_ounces(cups)
cups_to_ounces.py
Slide 18
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
Arguments are passed by position to the corresponding parameter variables in the function. This means
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
for the sum, and displays a message indicating the result.
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
Python functions
want to use them, you just the call the function. Examples are print,
input, range
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
Slide 22
– 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
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 24
accessible to all statements in the program
– 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
accessed
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
the parameter variable, but no statement outside of the function can access it.
Making changes to parameters
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
assignment statement outside all of the functions in a program, the variable is global in scope
# 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()
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
Recommendation: restrict the use of global variables
can change the value of a global variable and it is assigned a bad value, it can be hard to find the culprit.
a global variable, then you may have to modify the function.
the places that a global variable is used and modified.
Alternative
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
candidate to be defined as a global variable.
Slide 29
Slide 30
Statement Returns a value
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
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
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
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
define multiple values on the left side of the assignment statement
getNumbers() that returns multiple values that correspond to num1 and num2
def main(): # Get numbers num1, num2 = getNumbers()
...