DOC PREVIEW
USF CS 110 - Functions

This preview shows page 1-2-22-23 out of 23 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

FunctionsSlide 2Top-Down DesignPowerPoint PresentationFunction CallsModulesFunction DefinitionSlide 8Example - no inputCall to function meeting()ExercisesParameters/ArgumentsSlide 13Slide 14Slide 15Slide 16ScopeSlide 18Another ExampleSlide 20Return ValuesSlide 22Slide 23FunctionsFunctions•A set of statements (lines of code) that can be run repeatedly •Goals: Learning Python by Lutz and Ascher–Code reuse–Procedural decompositionTop-Down Design•Break problem into subproblems•Print HIHO in block letters1. print H2. print I3. print H4. print O•Write a function to solve each subproblemdef printH(): print "* *" print "***" print "* *" printdef printI(): print "***" print " * " print "***" printdef printO(): print " * " print "* *" print " * " printprintH()printI()printH()printO()Function Calls•We’ve seen a few:–my_num = input(“Enter number: “)–my_string = raw_input(“Enter string: “)•Syntax: function_name(parameters)•Other examples:–int(“7”) - converts the string “7” to an integer–str(9) - converts the integer 9 to a string–float(2) - converts the integer 2 to a float(2.0)•can be used to force floating point division: float(5)/2 = 2.5!Modules•A module groups together several functions•math is a common module•import math allows you to use the math functions•dot operator allows you to call math functions–syntax: module_name.function(parameters)import mathmath.floor(9.5)math.ceil(9.5)str(math.floor(9.4)) #function call as parameterFunction Definition•Step 1: Think about what your function will do, the input it requires, the result it will produce, and the side-effects it might have–printH •the function will display the letter H in star characters•it does not require input•it will not produce a result•the side-effect will be output displayed on the screenFunction Definition•Syntax:def function_name(parameters):statements•function_name can be anything - follow the rules for variable names•parameters are the input•statements are the code that gets executed•statements MUST be indented (all by the same number of spaces/tabs)Example - no input#definition of function to print a greeting#no input, no output, side-effect: greeting is displayeddef greeting(): print "Hello”greeting() #call to function greeting#definition of function to print a closing#no input, no output, side-effect: closing is displayeddef closing(): print "Goodbye"closing() #call to function closing#definition of function to print a greeting and closing#no input, no output, side-effect: greeting and closing displayeddef meeting(): greeting() #example of a function call from within closing() #a functionmeeting() #call to function meetingCall to function meeting()main mainmeetingmainmeetinggreetingmainmeetingmainmeetingclosingmainmeetingmain1765 - “Goodbye”43 - “Hello”2Exercises1. Copy and paste or save hiho.py into a new file.2. Modify the program so that it prints “FIFO”.3. Write a program with the following three functions:1. printFirstName - a function that prints your first name2. printLastName - a function that prints your last name3. printFullName - a function that prints your full nameMake sure to test each function by calling it. Verify that it produces the correct result/side-effect.Parameters/Arguments•Input for functions•Specify variable names in parameter listdef add(number1, number2):sum = number1 + number2 print “Sum: “, sum•When function add is called, two numbers must be passed as inputadd(3, 4)•Variable number1 gets the value 3 and variable number2 gets the value 4Parameters/Arguments•Values are assigned in order–the first value passed in the function call is assigned to the first parameter in the function definition>>> def taketwo(mynum, mystring):... print "mynum ", mynum... print "mystring ", mystring... >>> taketwo("hello", 7)mynum hellomystring 7Parameters/Arguments•Variables can be passed as parametersnumber1 = input("Enter first number: ")number2 = input("Enter second number: ")add(number1, number2)bob = input("Enter first number: ")alice = input("Enter second number: ")add(bob, alice)Parameters/Arguments•Pass by assignmentnumber1 = input("Enter first number: ")number2 = input("Enter second number: ")add(number1, number2)number1number2Names Objectsmainnumber1number2add34Parameters/Arguments•Pass by assignmentbob = input("Enter first number: ")alice = input("Enter second number: ")add(bob, alice)bobaliceNames Objectsmainnumber1number2add34Scope•Parameters and variables defined inside a function can only be accessed in that functiondef greeting(word): sentence = "The greeting is " + word + "."print sentenceTraceback (most recent call last): File "test.py", line 4, in ? print sentenceNameError: name 'sentence' is not definedScope•Parameters and variables defined inside a function can only be accessed in that functiondef greeting(word): sentence = "The greeting is " + word + "."print wordTraceback (most recent call last): File "test.py", line 4, in ? print sentenceNameError: name ’word' is not definedAnother Exampledef greeting(word): sentence = "The greeting is " + word + "." print sentencesentence = "This is not the greeting."print sentencegreeting("hello")print sentenceThis is not the greeting.The greeting is hello.This is not the greeting.Exercises1. Write a program with the following functions:1. add - this function takes as input two numbers, adds them, and displays the result2. subtract - this function takes as input two numbers, subtracts the second from the first, and displays the result3. multiply - this function takes as input two numbers, multiplies them, and displays the result4. quotient - this function takes as input two numbers, divides the first by the second, and displays the resultMake sure to test each function by calling it. Verify that it produces the correct result/side-effect.Return Values•Functions may return a value to the caller•Results should be saved in a variable–the function call should appear on the right side of an =#a function to get inputdef getprice(): price = input("Enter purchase price: ") return priceprice = getprice()TAX_RATE = .0825def getcost(): cost = input("Enter item cost: ") return costdef calctax(cost): tax = cost*TAX_RATE return taxdef


View Full Document

USF CS 110 - Functions

Download Functions
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Functions and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Functions 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?