360 likes | 651 Views
Functions. Introduction to Computing Science and Programming I. Functions. What you (should) already know about functions. Like functions in math, Python functions take input and return output. The input for a function is given with arguments. int(“34”) has the argument “34”
E N D
Functions Introduction to Computing Science and Programming I
Functions • What you (should) already know about functions. • Like functions in math, Python functions take input and return output. • The input for a function is given with arguments. • int(“34”) has the argument “34” • Arguments can be variables or expressions which may themselves include function calls. • str(x), str(x * 5) • int( raw_input(“Enter a number:”))
Built-In Functions • You’ve learned how to use, “call”, several of Python’s built-in functions that can be used in any program. • raw_input(“Enter text: “) • int(35.4), float(45), str(34) • len(“This is a string”) • round(34.6) • Now we will look at how to create and use our own functions.
Defining Functions • What do we need to include in a function definition. • Name • List of arguments • Documentation string to describe function • The actual code of the function which will include… • A return value, the output of the function
Defining Functions • Name • Follows the same rules as variable naming • As with variables, good code style requires intelligent, descriptive function names • findAverage, loadFile • Don’t give a variable and a function the same name as this obviously leads to confusion
Defining Functions • List of arguments • A list of arguments define the input that a function needs • A function may have no arguments • When a function is called, the values specified in the call are filled in • Arguments can handle any of Python’s data types
Defining Functions • Documentation String • A special one line comment that describes what the function does • Good code style requires that you have one of these lines for every function you define
Defining Functions • Return Value • When a function is complete it will use a return statement that specifies what value will be output from the function • Not all functions have output. They may perform a task, such as printing something to the screen, that does not have any output • The return value can be any of Python’s data types (Boolean, Integer…)
Defining Functions • A simple example def read_integer(prompt): """Read an integer from the user and return it.""" input = raw_input(prompt) return int(input)
Defining Functions def read_integer(prompt): """Read an integer from the user and return it.""" input = raw_input(prompt) return int(input) • The first line • def read_integer(prompt): • The def keyword is used signal the start of a function definition • Then we have the function name read_integer • Then inside parentheses we have the list of argument • As with a block of code for a loop or if statement, the lines for the rest of the function are indented
Defining Functions def read_integer(prompt): """Read an integer from the user and return it.""" input = raw_input(prompt) return int(input) • The first indented line is a triple quoted string. This is the special type of comment used to define what the function does. • The remaining lines are the actual code for the function
Defining Functions • Arguments • The function read_integer has one argument, prompt • Within the function, prompt acts as a variable that is initially assigned the value given from the calling code. • value = read_integer(“Enter a number: “) • When Python enters the function prompt will contain the string literal “Enter a number: “
Defining Functions • The return statement • Each function will have at least one line of the form ‘return expression’ When this line of code is executed the value of the expression is returned to the calling code. • Once a return statement is reached, no other code in the function will be executed
Defining Functions • You have to define a function to use it, so you need to have Python read the definition of the function before you use it. i.e. Place the function definition at the top of the file, and the code that uses it below. • Once you’ve run a file containing a function definition in the IDLE, then you can use that function in the interactive interpreter.
Calling Functions • What happens when you call a function? • When Python comes across a function call it must first evaluate the expressions for the arguments of the function. This may include other function calls. • The argument values are assigned to the argument variables inside the function • Execution leaves the current location and enters the function. • The function’s code is executed until a return statement, or the end of it’s code. • The return value of the function replaces the function call in the calling code. • Execution continues
Calling A Function def average(num1,num2,num3): """Returns the average of three numbers.""" total = num1+num2+num3 return total / 3.0 n1 = float(raw_input("Enter first number: ")) n2 = float(raw_input("Enter second number: ")) n3 = float(raw_input("Enter third number: ")) value = str( average (n1,n2,n3) / 3) print “One third of the average is ",value • What happens when we reach this line of code? Assume n1,n2,n3 have the values 1,2, and 3.
Calling A Function def average(num1,num2,num3): """Returns the average of three numbers.""" total = num1+num2+num3 return total / 3.0 n1 = float(raw_input("Enter first number: ")) n2 = float(raw_input("Enter second number: ")) n3 = float(raw_input("Enter third number: ")) value = str( average (n1,n2,n3) / 3) print “One third of the average is ",value • Python first sees the call to the function str(..), but it must first evaluate the expression for the single argument, average(n1,n2,n3) / 3
Calling A Function def average(num1,num2,num3): """Returns the average of three numbers.""" total = num1+num2+num3 return total / 3.0 n1 = float(raw_input("Enter first number: ")) n2 = float(raw_input("Enter second number: ")) n3 = float(raw_input("Enter third number: ")) value = str( average (n1,n2,n3) / 3) print “One third of the average is ",value • Before doing the division Python must get a value for average(n1,n2,n3) so it performs the function call.
Calling A Function def average(num1,num2,num3): """Returns the average of three numbers.""" total = num1+num2+num3 return total / 3.0 n1 = float(raw_input("Enter first number: ")) n2 = float(raw_input("Enter second number: ")) n3 = float(raw_input("Enter third number: ")) value = str( average (n1,n2,n3) / 3) print “One third of the average is ",value • The calling line of code is put on hold, and Python copies the argument values into the function. • num1 is assigned the value 1 stored in n1, etc.
Calling A Function def average(num1,num2,num3): """Returns the average of three numbers.""" total = num1+num2+num3 return total / 3.0 n1 = float(raw_input("Enter first number: ")) n2 = float(raw_input("Enter second number: ")) n3 = float(raw_input("Enter third number: ")) value = str( average (n1,n2,n3) / 3) print “One third of the average is ",value • We’re now in the function code, so the value of total is evaluated, 1+2+3 = 6
Calling A Function def average(num1,num2,num3): """Returns the average of three numbers.""" total = num1+num2+num3 return total / 3.0 n1 = float(raw_input("Enter first number: ")) n2 = float(raw_input("Enter second number: ")) n3 = float(raw_input("Enter third number: ")) value = str( average (n1,n2,n3) / 3) print “One third of the average is ",value • We’ve hit the return statement. Python evaluates the expression, total / 3.0 = 2.0 in this case. That value will be sent back to the calling code which has been on hold.
Calling A Function def average(num1,num2,num3): """Returns the average of three numbers.""" total = num1+num2+num3 return total / 3.0 n1 = float(raw_input("Enter first number: ")) n2 = float(raw_input("Enter second number: ")) n3 = float(raw_input("Enter third number: ")) value = str( average (n1,n2,n3) / 3) print “One third of the average is ",value • The return value of average(n1,n2,n3) is 2.0, so that is substituted into the expression and we have value=str(2.0/3)
Calling A Function def average(num1,num2,num3): """Returns the average of three numbers.""" total = num1+num2+num3 return total / 3.0 n1 = float(raw_input("Enter first number: ")) n2 = float(raw_input("Enter second number: ")) n3 = float(raw_input("Enter third number: ")) value = str( average (n1,n2,n3) / 3) print "One third of the average is ",value • Python evaluates 2.0/3 and sends it to the str() function. The code again waits for the return value which is “0.666…67” • That is then assigned to the variable value
Calling A Function def average(num1,num2,num3): """Returns the average of three numbers.""" total = num1+num2+num3 return total / 3.0 n1 = float(raw_input("Enter first number: ")) n2 = float(raw_input("Enter second number: ")) n3 = float(raw_input("Enter third number: ")) value = str( average (n1,n2,n3) / 3) print "One third of the average is ",value • Now at the final line of code, Python prints out the value calculated and stored in the previous line.
Argument/Return Types • In most programming languages, Java, C, C++, Visual Basic…, when you define a function you are forced to specify the data type of each argument and the data type that is going to be returned. • Python doesn’t have this requirement which can lead to errors if you are not careful about what data types you are using with your functions.
Argument/Return Types • A function in C++ //returns base to the exp power int power(int base,int exp){ int ans; ans = 1; for (int i = 1; i <=exp; i++) ans = ans * base; return ans; } • Don’t worry about understanding everything in the code. • The first word in the first line defines what type of value will be returned, integer, and the two variables, base and exp, are both of type integer. • C++ will not let you call the function unless you give it arguments of the proper type. It also will not let a function return a value that isn’t of the type specified.
Argument/Return Types • Since Python can not check if you are giving functions input of the proper type, you will not see problems until runtime. • If you send a function input of the wrong type it may cause an error that stops the program while it is running, or it may just produce incorrect results.
Why Use Functions? • It allows you to write code once and use it in many places. • You only have to debug the code in the function once. Once it is working you can use the function without worrying about it. • If you want to change the functionality, you only have to change code in one spot • Your code will look cleaner and be more readable • If you are copying the same piece of code to 2 or more spots in your program, it is likely that putting into a function is the best option
Why Use Functions? • It can be worthwhile moving code into a function, even if it will only be called once. • The separation of a task into smaller functions makes it easier to code/debug and to understand when you or someone else looks through the code.
Variable Scope • Variables that are created inside a function are only available inside that function. • These are called local variables, their scope is the code inside the function • Variables created outside a function are not available inside the function • Because of this separation variables inside and outside of a function with the same name will not interfere with each other
Variable Scope • You can think of each function as a ‘black box’. From the outside, you can’t see what it is doing. From the inside, you can’t see what’s going on outside. • When writing the function, you don’t have to worry about anything going on outside. Just define the input you need and return the proper output. • When calling the function, just assume you are give inputs to the ‘black box’ and that it will give you the right input; there’s no reason to be concerned with the workings inside.
Variable Scope def stars(num): starline = "" for i in range(num): starline = starline + "*" return starline num = int(raw_input("How many lines should I print? ")) for i in range(num): print stars(i+1) • An example where variables with the same name, i and num, won’t interfere with each other because of variable scope
Examples • Function with no arguments and no return value • Function that prints out the same message each time • Functions that are used just to break your code into chunks • Function with no arguments and a return value • A task that doesn’t depend on input, but does return a value.
Examples • Function with arguments, but no return value • Perform a task that requires input to define it, but has no output, printing to the screen for example • Functions with arguments and a return value
Examples • Boolean functions • Don’t forget that functions can return a Boolean • One situation where this can be useful is if you have a complicated condition for an if statement or a while loop. Write a function that evaluates the condition for you
Example • As mentioned earlier one reason to write functions is to make it easier to understand. • One situation where this happens is when you have nested loops. If you’re having trouble figuring out the logic you need, you might try moving the inner loop into a function that “hides” the loop. • Keep the same idea in mind whenever you have a complex task with or without loops