functions
play

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


  1. INLS 560 Programming for Information Professionals Functions Joan Boone jpboone@email.unc.edu Summer 2020 Slide 1

  2. Topics Part 1 ● Overview of functions Part 2 ● Function arguments Part 3 ● Variable scope Part 4 ● Value-returning functions Slide 2

  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 ● Slide 3 Source: Starting Out with Python by Tony Gaddis

  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 4

  5. Use Functions for Basic Tasks INPUT hours_worked = 40 hourly_pay_rate = 25.00 PROCESS gross_pay = hours_worked * hourly_pay_rate print(gross_pay) OUTPUT 1000.0 Slide 5

  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 6

  7. Use functions to 'divide and conquer' a large task A function is a group of statements that performs a specific task Input task: ● Get employee's hourly pay rate ● Get number of hours worked Process task: ● Calculate regular pay ● Calculate overtime pay Process task: ● Calculate deductions ● Calculate net pay Output task: ● Generate paycheck Slide 7 Source: Starting Out with Python by Tony Gaddis

  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 8

  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 9

  10. Defining and Calling Functions These statements define the display_message function so that it can be called by other statements in your program. # 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() This statement calls the display_message function, causing it to be executed. IMPORTANT: the function must be defined before it can be called. Slide 10 function_demo.py

  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 11

  12. Flow of Function Execution # This program has 2 functions # Define the main function def main(): print ('A quote from Albert Einstein:') display_message() 2 print('...in a letter to his son, 1930') 4 # Define the display_message function def display_message(): print('\tLife is like riding a bicycle.') print('\tTo keep your balance, you must keep moving.') 3 # Call the main function main() 1 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 12

  13. Payroll Program with Multiple Functions def main(): get_input() calculate_gross_pay() calculate_deductions() calculate_net_pay() Payroll program steps generate_paycheck() def get_input(): ● Get hours worked # get hours_worked ● Get hourly pay rate # get hourly_pay_rate ● Calculate regular pay def calculate_gross_pay(): # calculate regular_pay ● Calculate overtime pay # calculate overtime_pay # gross_pay = regular_pay + overtime_pay ● Calculate deductions ● Calculate net pay def calculate_deductions(): # calculate taxes ● Generate paycheck # calculate benefits # deductions = taxes + benefits def calculate_net_pay(): # net_pay = gross_pay - deductions def generate_paycheck(): # print paycheck or direct deposit main() Slide 13

  14. Topics Part 1 ● Overview of functions Part 2 ● Function arguments Part 3 ● Variable scope Part 4 ● Value-returning functions Slide 14

  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') Slide 15 Source: Starting Out with Python by Tony Gaddis

  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 # This program demonstrates an argument being # passed to a function some_number is a variable passed as an argument def main(): some_number = 5 show_double(some_number) # The show_double function accepts an argument # and displays double its value number is a parameter variable def show_double(number): result = number * 2 print(result) # Call the main function The value of the some_number variable main() is copied to the number variable, so both variables have a value of 5 Slide 16 Source: Starting Out with Python by Tony Gaddis pass_arg.py

  17. Another Example of Passing an Argument to a Function Hierarchy chart Design Display an introduction of ● main() what the program does Get the number of cups ● Convert cups to ounces and ● intro() cups_to_ounces(cups) display results # 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 ounces = cups * 8 print(cups, 'cups converts to', ounces, 'ounces.') main() Slide 17 cups_to_ounces.py Source: Starting Out with Python by Tony Gaddis

  18. Built-in Functions with Multiple Arguments print('Gross pay:', gross_pay) string label calculated result formatted_tax = format(tax, ',.2f') value to string with format format specification random_number = random.randint(1, 52) lower upper bound bound Slide 18 Source: Starting Out with Python by Tony Gaddis

  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) Called a parameter list, where def show_sum(num1, num2): variables are separated by commas 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() Source: Starting Out with Python Slide 19 by Tony Gaddis

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend