I Made a Function in Python Now I Want to See Its Code Again
Creating Functions
Overview
Educational activity: thirty min
Exercises: 0 minQuestions
How can I define new functions?
What's the difference betwixt defining and calling a role?
What happens when I phone call a function?
Objectives
Define a function that takes parameters.
Return a value from a function.
Test and debug a part.
Set default values for function parameters.
Explicate why we should divide programs into pocket-sized, single-purpose functions.
At this point, we've written code to describe some interesting features in our inflammation data, loop over all our information files to quickly describe these plots for each of them, and have Python make decisions based on what it sees in our data. But, our code is getting pretty long and complicated; what if we had thousands of datasets, and didn't want to generate a figure for every unmarried ane? Commenting out the figure-drawing code is a nuisance. Also, what if we want to use that code again, on a different dataset or at a unlike point in our programme? Cut and pasting it is going to brand our code get very long and very repetitive, very speedily. We'd like a mode to parcel our code so that it is easier to reuse, and Python provides for this by letting usa define things called 'functions' — a shorthand way of re-executing longer pieces of code. Let's start by defining a office fahr_to_celsius that converts temperatures from Fahrenheit to Celsius:
def fahr_to_celsius ( temp ): render (( temp - 32 ) * ( 5 / 9 ))
The function definition opens with the keyword def followed by the name of the part (fahr_to_celsius) and a parenthesized list of parameter names (temp). The body of the role — the statements that are executed when it runs — is indented below the definition line. The trunk concludes with a render keyword followed by the return value.
When we call the function, the values we laissez passer to information technology are assigned to those variables so that we can use them within the function. Within the function, we use a return statement to ship a result back to whoever asked for it.
Let'southward endeavor running our function.
This control should telephone call our function, using "32" every bit the input and return the function value.
In fact, calling our own function is no different from calling any other part:
impress ( 'freezing point of water:' , fahr_to_celsius ( 32 ), 'C' ) print ( 'boiling point of water:' , fahr_to_celsius ( 212 ), 'C' ) freezing point of h2o: 0.0 C boiling point of water: 100.0 C We've successfully called the function that we defined, and nosotros take access to the value that we returned.
Composing Functions
Now that we've seen how to plough Fahrenheit into Celsius, nosotros tin also write the part to turn Celsius into Kelvin:
def celsius_to_kelvin ( temp_c ): render temp_c + 273.15 impress ( 'freezing point of water in Kelvin:' , celsius_to_kelvin ( 0. )) freezing bespeak of h2o in Kelvin: 273.fifteen What about converting Fahrenheit to Kelvin? We could write out the formula, simply we don't need to. Instead, nosotros tin compose the 2 functions we have already created:
def fahr_to_kelvin ( temp_f ): temp_c = fahr_to_celsius ( temp_f ) temp_k = celsius_to_kelvin ( temp_c ) render temp_k print ( 'boiling point of water in Kelvin:' , fahr_to_kelvin ( 212.0 )) boiling signal of water in Kelvin: 373.15 This is our get-go taste of how larger programs are built: we define basic operations, then combine them in e'er-larger chunks to go the outcome we desire. Real-life functions will usually be larger than the ones shown here — typically half a dozen to a few dozen lines — but they shouldn't ever be much longer than that, or the next person who reads it won't exist able to understand what's going on.
Variable Telescopic
In composing our temperature conversion functions, we created variables inside of those functions, temp, temp_c, temp_f, and temp_k. We refer to these variables as local variables considering they no longer be one time the part is done executing. If we try to admission their values outside of the part, nosotros will encounter an fault:
impress ( 'Once more, temperature in Kelvin was:' , temp_k ) --------------------------------------------------------------------------- NameError Traceback (most recent phone call final) <ipython-input-1-eed2471d229b> in <module> ----> 1 print('Over again, temperature in Kelvin was:', temp_k) NameError: name 'temp_k' is not defined If you want to reuse the temperature in Kelvin afterwards you have calculated information technology with fahr_to_kelvin, yous can store the result of the part call in a variable:
temp_kelvin = fahr_to_kelvin ( 212.0 ) print ( 'temperature in Kelvin was:' , temp_kelvin ) temperature in Kelvin was: 373.fifteen The variable temp_kelvin, being defined outside any function, is said to be global.
Inside a function, one tin read the value of such global variables:
def print_temperatures (): print ( 'temperature in Fahrenheit was:' , temp_fahr ) impress ( 'temperature in Kelvin was:' , temp_kelvin ) temp_fahr = 212.0 temp_kelvin = fahr_to_kelvin ( temp_fahr ) print_temperatures () temperature in Fahrenheit was: 212.0 temperature in Kelvin was: 373.fifteen Tidying upwards
Now that nosotros know how to wrap bits of code up in functions, nosotros can make our inflammation assay easier to read and easier to reuse. Offset, let'southward make a visualize function that generates our plots:
def visualize ( filename ): data = numpy . loadtxt ( fname = filename , delimiter = ',' ) fig = matplotlib . pyplot . effigy ( figsize = ( 10.0 , iii.0 )) axes1 = fig . add_subplot ( 1 , 3 , i ) axes2 = fig . add_subplot ( 1 , iii , 2 ) axes3 = fig . add_subplot ( ane , 3 , three ) axes1 . set_ylabel ( 'average' ) axes1 . plot ( numpy . mean ( data , axis = 0 )) axes2 . set_ylabel ( 'max' ) axes2 . plot ( numpy . max ( data , centrality = 0 )) axes3 . set_ylabel ( 'min' ) axes3 . plot ( numpy . min ( information , axis = 0 )) fig . tight_layout () matplotlib . pyplot . evidence () and another role chosen detect_problems that checks for those systematics we noticed:
def detect_problems ( filename ): data = numpy . loadtxt ( fname = filename , delimiter = ',' ) if numpy . max ( information , axis = 0 )[ 0 ] == 0 and numpy . max ( information , axis = 0 )[ twenty ] == 20 : impress ( 'Suspicious looking maxima!' ) elif numpy . sum ( numpy . min ( data , axis = 0 )) == 0 : impress ( 'Minima add together up to naught!' ) else : print ( 'Seems OK!' ) Wait! Didn't we forget to specify what both of these functions should return? Well, nosotros didn't. In Python, functions are non required to include a return statement and tin can be used for the sole purpose of group together pieces of lawmaking that conceptually exercise i affair. In such cases, role names usually describe what they do, e.g. visualize, detect_problems.
Notice that rather than jumbling this code together in one giant for loop, nosotros can now read and reuse both ideas separately. Nosotros can reproduce the previous analysis with a much simpler for loop:
filenames = sorted ( glob . glob ( 'inflammation*.csv' )) for filename in filenames [: three ]: print ( filename ) visualize ( filename ) detect_problems ( filename ) Past giving our functions human-readable names, we tin can more than easily read and sympathize what is happening in the for loop. Even better, if at some later date we want to utilize either of those pieces of code again, nosotros can do so in a single line.
Testing and Documenting
Once we get-go putting things in functions so that we can re-use them, we need to start testing that those functions are working correctly. To meet how to do this, allow's write a function to start a dataset so that information technology'south mean value shifts to a user-defined value:
def offset_mean ( data , target_mean_value ): return ( data - numpy . mean ( information )) + target_mean_value We could test this on our bodily information, but since we don't know what the values ought to be, information technology will exist hard to tell if the result was right. Instead, let'southward use NumPy to create a matrix of 0's and and then offset its values to have a mean value of 3:
z = numpy . zeros (( ii , 2 )) impress ( offset_mean ( z , 3 )) That looks correct, so let's try offset_mean on our real data:
data = numpy . loadtxt ( fname = 'inflammation-01.csv' , delimiter = ',' ) print ( offset_mean ( data , 0 )) [[-6.14875 -vi.14875 -v.14875 ... -3.14875 -6.14875 -half dozen.14875] [-6.14875 -5.14875 -4.14875 ... -v.14875 -6.14875 -five.14875] [-6.14875 -5.14875 -5.14875 ... -4.14875 -5.14875 -5.14875] ... [-6.14875 -five.14875 -5.14875 ... -5.14875 -5.14875 -v.14875] [-6.14875 -half dozen.14875 -6.14875 ... -six.14875 -iv.14875 -vi.14875] [-6.14875 -6.14875 -v.14875 ... -five.14875 -5.14875 -6.14875]] Information technology's hard to tell from the default output whether the effect is correct, only there are a few tests that we can run to reassure united states:
print ( 'original min, mean, and max are:' , numpy . min ( information ), numpy . mean ( data ), numpy . max ( data )) offset_data = offset_mean ( data , 0 ) impress ( 'min, mean, and max of offset data are:' , numpy . min ( offset_data ), numpy . mean ( offset_data ), numpy . max ( offset_data )) original min, mean, and max are: 0.0 6.14875 20.0 min, hateful, and and max of offset data are: -six.14875 2.84217094304e-16 13.85125 That seems virtually correct: the original mean was about six.1, so the lower bound from zero is now about -6.i. The mean of the offset data isn't quite zero — we'll explore why not in the challenges — but it'due south pretty shut. Nosotros can even go further and cheque that the standard departure hasn't changed:
print ( 'std dev before and afterward:' , numpy . std ( data ), numpy . std ( offset_data )) std dev before and after: 4.61383319712 4.61383319712 Those values look the same, but we probably wouldn't discover if they were dissimilar in the sixth decimal place. Let's do this instead:
print ( 'difference in standard deviations before and afterward:' , numpy . std ( data ) - numpy . std ( offset_data )) difference in standard deviations before and after: -three.5527136788e-15 Again, the difference is very small. Information technology's still possible that our function is incorrect, but information technology seems unlikely plenty that we should probably get back to doing our assay. We have ane more than task showtime, though: we should write some documentation for our function to remind ourselves later what it'due south for and how to use it.
The usual way to put documentation in software is to add together comments like this:
# offset_mean(data, target_mean_value): # return a new array containing the original information with its hateful offset to friction match the desired value. def offset_mean ( data , target_mean_value ): return ( information - numpy . mean ( data )) + target_mean_value There's a better way, though. If the showtime thing in a office is a string that isn't assigned to a variable, that string is attached to the function as its documentation:
def offset_mean ( data , target_mean_value ): """Return a new array containing the original data with its mean offset to friction match the desired value.""" return ( data - numpy . hateful ( data )) + target_mean_value This is amend because we can at present ask Python's built-in help system to show us the documentation for the function:
Help on office offset_mean in module __main__: offset_mean(data, target_mean_value) Render a new array containing the original information with its hateful offset to friction match the desired value. A string like this is chosen a docstring. We don't need to use triple quotes when we write i, simply if we do, we can suspension the string across multiple lines:
def offset_mean ( data , target_mean_value ): """Return a new array containing the original data with its mean offset to lucifer the desired value. Examples -------- >>> offset_mean([1, 2, 3], 0) array([-i., 0., 1.]) """ render ( information - numpy . hateful ( data )) + target_mean_value help ( offset_mean ) Help on part offset_mean in module __main__: offset_mean(data, target_mean_value) Return a new array containing the original data with its mean offset to lucifer the desired value. Examples -------- >>> offset_mean([1, 2, 3], 0) assortment([-1., 0., 1.]) Defining Defaults
Nosotros have passed parameters to functions in two means: straight, equally in blazon(information), and by name, every bit in numpy.loadtxt(fname='something.csv', delimiter=','). In fact, we tin can laissez passer the filename to loadtxt without the fname=:
numpy . loadtxt ( 'inflammation-01.csv' , delimiter = ',' ) array([[ 0., 0., 1., ..., 3., 0., 0.], [ 0., 1., two., ..., 1., 0., one.], [ 0., 1., i., ..., 2., 1., 1.], ..., [ 0., 1., i., ..., 1., i., 1.], [ 0., 0., 0., ..., 0., 2., 0.], [ 0., 0., 1., ..., 1., i., 0.]]) simply we nonetheless need to say delimiter=:
numpy . loadtxt ( 'inflammation-01.csv' , ',' ) Traceback (near recent telephone call last): File "<stdin>", line 1, in <module> File "/Users/username/anaconda3/lib/python3.6/site-packages/numpy/lib/npyio.py", line 1041, in loa dtxt dtype = np.dtype(dtype) File "/Users/username/anaconda3/lib/python3.half dozen/site-packages/numpy/core/_internal.py", line 199, in _commastring newitem = (dtype, eval(repeats)) File "<string>", line 1 , ^ SyntaxError: unexpected EOF while parsing To sympathize what'southward going on, and make our own functions easier to use, let's re-define our offset_mean function like this:
def offset_mean ( data , target_mean_value = 0.0 ): """Render a new array containing the original information with its mean offset to match the desired value, (0 by default). Examples -------- >>> offset_mean([1, 2, 3]) assortment([-1., 0., i.]) """ render ( information - numpy . mean ( information )) + target_mean_value The key change is that the second parameter is now written target_mean_value=0.0 instead of just target_mean_value. If we phone call the function with two arguments, it works as it did earlier:
test_data = numpy . zeros (( ii , 2 )) print ( offset_mean ( test_data , three )) But we tin can as well now call it with merely ane parameter, in which case target_mean_value is automatically assigned the default value of 0.0:
more_data = 5 + numpy . zeros (( two , ii )) print ( 'data before mean starting time:' ) print ( more_data ) print ( 'beginning data:' ) impress ( offset_mean ( more_data )) data earlier mean offset: [[ 5. v.] [ 5. v.]] offset information: [[ 0. 0.] [ 0. 0.]] This is handy: if nosotros ordinarily want a function to work one mode, but occasionally need it to exercise something else, we tin can let people to pass a parameter when they need to merely provide a default to brand the normal case easier. The example below shows how Python matches values to parameters:
def display ( a = 1 , b = 2 , c = 3 ): print ( 'a:' , a , 'b:' , b , 'c:' , c ) print ( 'no parameters:' ) display () print ( 'one parameter:' ) display ( 55 ) impress ( 'two parameters:' ) display ( 55 , 66 ) no parameters: a: one b: 2 c: 3 ane parameter: a: 55 b: 2 c: 3 two parameters: a: 55 b: 66 c: iii As this example shows, parameters are matched upwards from left to right, and any that haven't been given a value explicitly get their default value. We tin can override this behavior by naming the value as we laissez passer it in:
impress ( 'only setting the value of c' ) display ( c = 77 ) just setting the value of c a: i b: ii c: 77 With that in hand, let's expect at the help for numpy.loadtxt:
Help on function loadtxt in module numpy.lib.npyio: loadtxt(fname, dtype=<course 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, apply cols=None, unpack=Fake, ndmin=0, encoding='bytes') Load data from a text file. Each row in the text file must accept the aforementioned number of values. Parameters ---------- ... There'south a lot of information here, but the most important part is the first couple of lines:
loadtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, apply cols=None, unpack=False, ndmin=0, encoding='bytes') This tells united states that loadtxt has ane parameter called fname that doesn't take a default value, and eight others that do. If nosotros call the function like this:
numpy . loadtxt ( 'inflammation-01.csv' , ',' ) so the filename is assigned to fname (which is what nosotros want), just the delimiter string ',' is assigned to dtype rather than delimiter, because dtype is the second parameter in the list. However ',' isn't a known dtype so our code produced an error message when nosotros tried to run information technology. When we telephone call loadtxt we don't have to provide fname= for the filename because it's the beginning particular in the list, but if we want the ',' to exist assigned to the variable delimiter, we exercise have to provide delimiter= for the second parameter since delimiter is non the second parameter in the listing.
Readable functions
Consider these two functions:
def southward ( p ): a = 0 for v in p : a += v k = a / len ( p ) d = 0 for v in p : d += ( v - m ) * ( v - grand ) return numpy . sqrt ( d / ( len ( p ) - 1 )) def std_dev ( sample ): sample_sum = 0 for value in sample : sample_sum += value sample_mean = sample_sum / len ( sample ) sum_squared_devs = 0 for value in sample : sum_squared_devs += ( value - sample_mean ) * ( value - sample_mean ) render numpy . sqrt ( sum_squared_devs / ( len ( sample ) - 1 )) The functions s and std_dev are computationally equivalent (they both calculate the sample standard departure), but to a human reader, they expect very different. Yous probably found std_dev much easier to read and understand than south.
As this example illustrates, both documentation and a developer's coding style combine to determine how easy information technology is for others to read and understand the programmer'south code. Choosing meaningful variable names and using blank spaces to break the code into logical "chunks" are helpful techniques for producing readable code. This is useful not simply for sharing code with others, but too for the original programmer. If you demand to revisit code that yous wrote months ago and haven't idea virtually since so, you lot volition appreciate the value of readable code!
Combining Strings
"Adding" two strings produces their concatenation:
'a' + 'b'is'ab'. Write a function calleddebatethat takes 2 parameters calledoriginalandwrapperand returns a new string that has the wrapper graphic symbol at the beginning and end of the original. A telephone call to your role should wait similar this:print ( fence ( 'name' , '*' ))Solution
def contend ( original , wrapper ): return wrapper + original + wrapper
Return versus print
Note that
renderandreturnargument, on the other mitt, makes data visible to the program. Let'due south have a look at the following function:def add ( a , b ): print ( a + b )Question: What volition we see if nosotros execute the post-obit commands?
Solution
Python will first execute the function
addwitha = sevenandb = three, and, therefore, print10. All the same, because partadddoes not have a line that starts withreturn(noreturn"statement"), it will, by default, return nothing which, in Python world, is calledNone. Therefore,Awill be assigned toNoneand the concluding line (print(A)) will printNone. As a outcome, we will see:
Selecting Characters From Strings
If the variable
srefers to a string, sos[0]is the string'due south first character andsouthward[-1]is its last. Write a function calledouterthat returns a string made upwardly of just the first and final characters of its input. A call to your function should look like this:Solution
def outer ( input_string ): render input_string [ 0 ] + input_string [ - ane ]
Rescaling an Assortment
Write a function
rescalethat takes an array every bit input and returns a respective assortment of values scaled to lie in the range 0.0 to 1.0. (Hint: IfFiftyandHare the everyman and highest values in the original array, and then the replacement for a valuevshould be(v-Fifty) / (H-L).)Solution
def rescale ( input_array ): Fifty = numpy . min ( input_array ) H = numpy . max ( input_array ) output_array = ( input_array - L ) / ( H - Fifty ) return output_array
Testing and Documenting Your Office
Run the commands
aid(numpy.arange)andhelp(numpy.linspace)to see how to use these functions to generate regularly-spaced values, and then use those values to examination yourrescaleoffice. In one case y'all've successfully tested your function, add a docstring that explains what it does.Solution
"""Takes an array as input, and returns a corresponding array scaled then that 0 corresponds to the minimum and 1 to the maximum value of the input assortment. Examples: >>> rescale(numpy.arange(10.0)) array([ 0. , 0.11111111, 0.22222222, 0.33333333, 0.44444444, 0.55555556, 0.66666667, 0.77777778, 0.88888889, one. ]) >>> rescale(numpy.linspace(0, 100, 5)) assortment([ 0. , 0.25, 0.5 , 0.75, i. ]) """
Defining Defaults
Rewrite the
rescalefunction so that it scales information to prevarication between0.0and1.0by default, merely will let the caller to specify lower and upper bounds if they desire. Compare your implementation to your neighbor'due south: do the two functions always deport the same way?Solution
def rescale ( input_array , low_val = 0.0 , high_val = 1.0 ): """rescales input array values to lie between low_val and high_val""" L = numpy . min ( input_array ) H = numpy . max ( input_array ) intermed_array = ( input_array - Fifty ) / ( H - L ) output_array = intermed_array * ( high_val - low_val ) + low_val return output_array
Variables Inside and Outside Functions
What does the following piece of code brandish when run — and why?
f = 0 thousand = 0 def f2k ( f ): thousand = (( f - 32 ) * ( 5.0 / 9.0 )) + 273.15 return k print ( f2k ( 8 )) print ( f2k ( 41 )) print ( f2k ( 32 )) print ( k )Solution
259.81666666666666 278.fifteen 273.fifteen 0
kis 0 because thekinside the rolef2kdoesn't know nigh thethoudefined outside the office. When thef2kfunction is called, it creates a local variablegrand. The function does non render any values and does not alterkoutside of its local copy. Therefore the original value ofthouremains unchanged. Beware that a localone thousandis created becausef2kinternal statements affect a new value to it. Ifkwas onlyread, it would simply retreive the globalkvalue.
Mixing Default and Non-Default Parameters
Given the following code:
def numbers ( one , two = 2 , three , four = 4 ): due north = str ( i ) + str ( ii ) + str ( three ) + str ( 4 ) return n print ( numbers ( 1 , three = iii ))what do y'all expect will be printed? What is actually printed? What dominion practice you think Python is post-obit?
1234one2three41239SyntaxErrorGiven that, what does the post-obit piece of lawmaking display when run?
def func ( a , b = 3 , c = 6 ): print ( 'a: ' , a , 'b: ' , b , 'c:' , c ) func ( - 1 , ii )
a: b: 3 c: 6a: -1 b: three c: half dozena: -1 b: 2 c: via: b: -1 c: 2Solution
Attempting to define the
numbersfunction results in4. SyntaxError. The defined parameterstwoandfourare given default values. Becauseoneandthreeare non given default values, they are required to exist included as arguments when the role is chosen and must exist placed earlier any parameters that accept default values in the office definition.The given call to
funcdisplaysa: -1 b: ii c: 6. -1 is assigned to the beginning parametera, 2 is assigned to the next parameterb, andcis not passed a value, so it uses its default value 6.
Readable Code
Revise a function you wrote for one of the previous exercises to try to make the code more readable. Then, collaborate with 1 of your neighbors to critique each other's functions and discuss how your office implementations could be further improved to make them more readable.
Key Points
Ascertain a function using
def function_name(parameter).The body of a role must exist indented.
Call a function using
function_name(value).Numbers are stored as integers or floating-point numbers.
Variables defined inside a function can only be seen and used within the body of the function.
Variables created outside of any function are called global variables.
Inside a role, we tin access global variables.
Variables created within a function override global variables if their names match.
Utilize
assistance(thing)to view assist for something.Put docstrings in functions to provide help for that office.
Specify default values for parameters when defining a function using
name=valuein the parameter list.Parameters can be passed by matching based on proper name, by position, or by omitting them (in which case the default value is used).
Put lawmaking whose parameters alter oftentimes in a part, and then call it with different parameter values to customize its behavior.
Source: https://swcarpentry.github.io/python-novice-inflammation/08-func/index.html
0 Response to "I Made a Function in Python Now I Want to See Its Code Again"
Post a Comment