190 likes | 203 Views
Learn about functions in programming, their structure, how to pass parameters, and handle errors. Improve code reusability and readability.
E N D
Takes one or more arguments, or perhaps none at all Performs an operation Returns one or more values, or perhaps none at all Similar to mathematical functions What is a Function?
Functions make code more manageable: Can reuse code. Makes code more readable. Enables programmer to break complicated projects down into simpler parts. Why Use Functions?
A function is defined as follows def my_function(): …. Do processing ….. return A function definition is indicated by the keyword, def, followed by the name of the function, parameters if any, and a colon. Code that is part of the function is indented. This function ends with a return statement. The Structure of Functions
In the example on the previous slide, no arguments are accepted by the function and no value is returned. Since no value is returned, it is not necessary to end the function with a return statement. The end of the function definition is indicated by the first line of code that is not indented. Functions are invoked by the function statements. Compare the two simple function definitions and their invocation. def my_function_a(): print('Inside my_function_a') return def my_function_b(): print('Inside my_function_b') print('After my_function_a and my_function_b') my_function_a() my_function_b() The Structure of Functions cont'd
In the following function we pass a floating point number to the function. The function returns a floating point. import math def calculate_sphere_volume(r): vol = 4 * math.pi * 3 / r**3 return vol radius = float(input('Input a radius ')) vol = calculate_sphere_volume(radius) print('The volume is ' + str(vol)) We've imported the math package so we could use pi. Also, the function input always returns a string value which is why we had to explicitly cast the input as a float. Also, we had to explicitly cast the vol variable to a string in the print statement. Passing Parameters to Functions
This is the same code as on the previous slide, except that we've incorporated error handling via a try-except block. The user might not enter a number, so the try-except enables the code to exit gracefully. import math def calculate_sphere_volume(radius): vol = 4 * math.pi * 3 / radius**3 return vol try: radius = float(input('Input a radius ')) vol = calculate_sphere_volume(radius) print('The volume is ' + str(vol)) except Exception: print('You did not enter a number!') Passing Parameters to Functions: Better Error Handling
Notice that the try-except block only encloses the input statement, the function invocation, and the print volume statement. If the user failed to enter a number then no further statements in the try suite of code will be executed and the print error statement in the except suite of code will be executed. By including the function invocation and the print volume statements in the try suite of code, we guarantee that those statements will not be executed if the user enters invalid data. And that is what we want. As you write more complicated pieces of code, the possibility of different exceptions occurring will arise, and you the programmer would likely wish to handle those exceptions differently. Change the word Exception to the word ValueError, which is the specific kind of error thrown when a user fails to input a number. Passing Parameters to Functions: Better Error Handling Page 2
In the following function we pass an integer and a float to the function. The function returns a floating point. def my_series(x,n): sum = 0 for i in range(0,n+1): sum += (-x)**i return sum x = float(input('Input a floating point number between 0 and 1: ')) n = int(input('Enter an integer between 1 and 10')) answer = my_series(x,n) print('The answer is ' + str(answer)) In the function definition, we wish to iterate from i = 0 up to i = n. If we had written (0,n), the for-loop would have iterated only from 0 up to n-1. Notice too, the casting of variables. Passing Parameters to Functions:Another Example
This code calculates the same series as on the previous slide, only now we've included error handling. Notice what code is placed inside of try-except block. def my_series(x,n): sum = 0 for i in range(0,n+1): sum += (-x)**i return sum try: x = float(input('Input a floating point number between 0 and 1: ')) n = int(input('Enter an integer between 1 and 10')) answer = my_series(x,n) print('The answer is ' + str(answer)) except Exception: print('You did not enter a number') Passing Parameters to Functions:Better Error Handling
When you define a function, you might want to give the user of option to either provide values for parameters or to use default parameters. You've already used a function that has default parameters and that is the show_message method of the SenseHat object. Let's revisit the show_message method. from sense_hat import SenseHat sense = SenseHat() sense.show_message('Good day') The Sense Hat displays the message, Good day, with the default scroll speed of 0.1, the default text color of white, and the default background color of black. In case you don't recall the arguments of the show_message function, if you pause after typing sense.show_message( in the Python shell, Python will display the parameters, including default values. Default Parameters
Here are other ways of using the show_message method: sense.show_message('Good day',scroll_speed=0.2) sense.show_message('Good day',scroll_speed=0.05, text_colour=[100,255,0]) sense.show_message('Good day',scroll_speed=0.08,text_colour=[100,255,0], back_colour=[255,255,255]) Notice that the British spelling of the word color must be used. Also, colors are given as lists of red, green, and blue components, and possible values of each range from 0 to 255. Default Parameters
The show_message method can also be invoked without explicitly entering the words scroll_speed, text_colour, and back_colour: sense.show_message('Good day',0.08,[0,0,255],[255,0,0]) Notice that the British spelling of the word color must be used. Also, colors are given as lists of red, green, and blue components, and possible values of each range from 0 to 255. If you do not explicitly enter the words scroll_speed, text_colour, and back_colour, the values you enter must be entered in order. More on Default Parameters
Consider a function that has default values for two arguments: def my_function(s='Good day', x = 9.8): print('s = ' + s) print('x = ' + str(x)) Type in the following function invocations to see what is printed out. my_function() my_function(s='Bon Jour',x=3.5) my_function(x=2.14, s='Buenos Dias') my_function('Willkommen',10) A Default Parameter Example
Functions can return more than one value. Consider the following very simple function that returns two values, an integer and a string. In order to retrieve the values, you type in two variable names separated by a comma, and both of which are followed by the function invocation. def my_function(): return 35, 'Grocery List' value, s = my_function() print('value = '+str(value)) print('s = '+s) Functions that Return More than One Value
If a variable is assigned a value within a function then that variable is not accessible from other parts of the code. That variable has local scope. def do_calculation(): x = 4.5 y = 3.2 tri = (x**2 + y**2)/5.0 return tri result = do_calculation() print(‘result = ' + str(result)) The above code is correct; the print statement prints out the value of the variable, returned from the function. Scope of Variables: A Preliminary Discussion
The following code is NOT correct because the print statement is outside the function. The variable, tri, is defined only within the function, so an error will occur if you attempt to access the variable outside. def do_calculation(): x = 4.5 y = 3.2 tri = (x**2 + y**2)/5.0 return do_calculation() print('tri = ' + str(tri)) Scope of Variables: A Preliminary Discussion Continued
def compute_area(height:float,width:float)->float: """This function was written by your name to compute the area of a triangle. ""“ pass print(compute_area.__doc__) # prints the document indicated in the ""“ double-quotes print(compute_area.__annotations__) # prints the parameters and the returned values print(compute_area.__str__) # prints all of the information about the function Documentation
Do not read in values within a function, unless the function is a main function or the function’s only task is to read in value. Do not print out values within a function, unless the function is a main function or the function’s only task is to write out value. The input and output tasks should be kept separate from the tasks of the function. You will need to pass in data as an argument to the parameters of the function. Function Design
defmy_series(x,n): sum = 0 for i in range(0,n+1): sum += (-x)**i return sum def main(): try: x = float(input('Input a floating point number between 0 and 1: ')) n = int(input('Enter an integer between 1 and 10')) answer = my_series(x,n) print('The answer is ' + str(answer)) except Exception: print('You did not enter a number') main() Function Design Example