Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Python Programming/Functions

From Wikibooks, open books for an open world
<Python Programming
Previous: LoopsIndexNext: Scoping


Function Calls

[edit |edit source]

Acallable object is an object that can accept some arguments (also called parameters) and possibly return an object (often a tuple containing multiple objects).

A function is the simplest callable object in Python, but there are others, such asclasses or certain class instances.

Defining Functions

[edit |edit source]

A function is defined in Python by the following format:

deffunctionname(arg1,arg2,...):statement1statement2...
>>>deffunctionname(arg1,arg2):...returnarg1+arg2...>>>t=functionname(24,24)# Result: 48

If a function takes no arguments, it must still include the parentheses, but without anything in them:

deffunctionname():statement1statement2...

The arguments in the function definition bind the arguments passed at function invocation (i.e. when the function is called), which are called actual parameters, to the names given when the function is defined, which are called formal parameters. The interior of the function has no knowledge of the names given to the actual parameters; the names of the actual parameters may not even be accessible (they could be inside another function).

A function can 'return' a value, for example:

defsquare(x):returnx*x

A function can define variables within the function body, which are considered 'local' to the function. The locals together with the arguments comprise all the variables within the scope of the function. Any names within the function are unbound when the function returns or reaches the end of the function body.

You canreturn multiple values as follows:

deffirst2items(list1):returnlist1[0],list1[1]a,b=first2items(["Hello","world","hi","universe"])print(a+" "+b)

Keywords: returning multiple values, multiple return values.

Declaring Arguments

[edit |edit source]

When calling a function that takes some values for further processing, we need to send some values as FunctionArguments. For example:

>>>deffind_max(a,b):if(a>b):returnstr(a)+" is greater than "+str(b)elif(b>a):returnstr(b)+" is greater than "+str(a)>>>find_max(30,45)#Here (30, 45) are the arguments passing for finding max between this two numbersTheoutputwillbe:45isgreaterthan30

Default Argument Values

[edit |edit source]

If any of the formal parameters in the function definition are declared with the format "arg = value," then you will have the option of not specifying a value for those arguments when calling the function. If you do not specify a value, then that parameter will have the default value given when the function executes.

>>>defdisplay_message(message,truncate_after=4):...print(message[:truncate_after])...>>>display_message("message")mess>>>display_message("message",6)messag

Links:

Variable-Length Argument Lists

[edit |edit source]

Python allows you to declare two special arguments which allow you to create arbitrary-length argument lists. This means that each time you call the function, you can specify any number of arguments above a certain number.

deffunction(first,second,*remaining):statement1statement2...

When calling the above function, you must provide value for each of the first two arguments. However, since the third parameter is marked with an asterisk, any actual parameters after the first two will be packed into a tuple and bound to "remaining."

>>>defprint_tail(first,*tail):...print(tail)...>>>print_tail(1,5,2,"omega")(5,2,'omega')

If we declare a formal parameter prefixed withtwo asterisks, then it will be bound to a dictionary containing any keyword arguments in the actual parameters which do not correspond to any formal parameters. For example, consider the function:

defmake_dictionary(max_length=10,**entries):returndict([(key,entries[key])fori,keyinenumerate(entries.keys())ifi<max_length])

If we call this function with any keyword arguments other than max_length, they will be placed in the dictionary "entries." If we include the keyword argument of max_length, it will be bound to theformal parameter max_length, as usual.

>>>make_dictionary(max_length=2,key1=5,key2=7,key3=9){'key3':9,'key2':7}

Links:

By Value and by Reference

[edit |edit source]

Objects passed as arguments to functions are passedby reference; they are not being copied around. Thus, passing a large list as an argument does not involve copying all its members to a new location in memory. Note that even integers are objects. However, the distinction ofby value andby reference present in some other programming languages often serves to distinguish whether the passed arguments can beactually changed by the called function and whether thecalling function can see the changes.

Passed objects ofmutable types such as lists and dictionaries can be changed by the called function and the changes are visible to the calling function. Passed objects ofimmutable types such as integers and strings cannot be changed by the called function; the calling function can be certain that the called function will not change them. For mutability, see alsoData Types chapter.

An example:

defappendItem(ilist,item):ilist.append(item)# Modifies ilist in a way visible to the callerdefreplaceItems(ilist,newcontentlist):delilist[:]# Modification visible to the callerilist.extend(newcontentlist)# Modification visible to the callerilist=[5,6]# No outside effect; lets the local ilist point to a new list object,# losing the reference to the list object passed as an argumentdefclearSet(iset):iset.clear()deftryToTouchAnInteger(iint):iint+=1# No outside effect; lets the local iint to point to a new int object,# losing the reference to the int object passed as an argumentprint("iint inside:",iint)# 4 if iint was 3 on function entrylist1=[1,2]appendItem(list1,3)print(list1)# [1, 2, 3]replaceItems(list1,[3,4])print(list1)# [3, 4]set1=set([1,2])clearSet(set1)print(set1)# set([])int1=3tryToTouchAnInteger(int1)print(int1)# 3

Preventing Argument Change

[edit |edit source]

If an argument is of an immutable type any changes made to it will remain local to the called function. However, if the argument is of a mutable type, such as a list, changes made to it will update the corresponding value in the calling function. Thus, if the calling function wants to make sure its mutable value passed to some unknown function will not be changed by it must create and pass a copy of the value.

An example:

defevil_get_length(ilist):length=len(ilist)delilist[:]# Muhaha: clear the listreturnlengthlist1=[1,2]print(evil_get_length(list1[:]))# Pass a copy of list1print(list1)# list1 = [1, 2]print(evil_get_length(list1))# list1 gets clearedprint(list1)# list1 = []

Calling Functions

[edit |edit source]

A function can be called by appending the arguments in parentheses to the function name or an empty pair of parentheses if the function takes no arguments.

foo()square(3)bar(5,x)

A function's return value can be used by assigning it to a variable, like so:

x=foo()y=bar(5,x)

As shown above, when calling a function you can specify the parameters by name and you can do so in any order

defdisplay_message(message,start=0,end=4):print(message[start:end])display_message("message",end=3)

This above is valid and start will have the default value of 0. A restriction placed on this is after the first named argument then all arguments after it must also be named. The following is not valid

display_message(end=5,start=1,"my message")

because the third argument ("my message") is an unnamed argument.

Nested functions

[edit |edit source]

Nested functions are functions defined within other functions. Arbitrary level of nesting is possible.

Nested functions can read variables declared in the immediately outside function. For such variables that are mutable, nested functions can even modify them. For such variables that are immutable such as integers, attempt at modification in the nested function throws UnboundLocalError. In Python 3, an immutable immediately outside variable can be declared in the nested function to benonlocal, in an analogy toglobal. Once this is done, the nested function can assign a new value to that variable and that modification is going to be seen outside of the nested function.

Nested functions can be used in#Closures, as shown below. Furthermore, they can be used to reduce repetion of code that pertains only to a single function, often with reduced argument list owing to seeing the immediately outside variables.

An example of a nested function that modifies an immediately outside variable that is a list and therefore mutable:

defoutside():outsideList=[1,2]defnested():outsideList.append(3)nested()print(outsideList)

An example in which the outside variable is first accessedbelow the nested function definition and it still works:

defoutside():defnested():outsideList.append(3)outsideList=[1,2]nested()print(outsideList)

Keywords: inner functions, internal functions, local functions.

Links:

Lambda Expressions

[edit |edit source]

A lambda is an anonymous (unnamed) function. It is used primarily to write very short functions that are a hassle to define in the normal way. A function like this:

>>>defadd(a,b):...returna+b...>>>add(4,3)7

may also be defined using lambda

>>>print((lambdaa,b:a+b)(4,3))7

Lambda is often used as an argument to other functions that expects a function object, such as sorted()'s 'key' argument.

>>>sorted([[3,4],[3,5],[1,2],[7,3]],key=lambdax:x[1])[[1,2],[7,3],[3,4],[3,5]]

The lambda form is often useful as a closure, such as illustrated in the following example:

>>>defattribution(name):...returnlambdax:x+' -- '+name...>>>pp=attribution('John')>>>pp('Dinner is in the fridge')'Dinner is in the fridge -- John'

Note that the lambda function can use the values of variables from thescope in which it was created similar to regular locally defined functions described above. In fact, exporting the precalculations embodiedby its constructor function is one of the essential utilities of closures.

Links:

Generator Functions

[edit |edit source]

When discussing loops, you came across the concept of aniterator. This yields in turn each element of some sequence, rather than the entire sequence at once, allowing you to deal with sequences much larger than might be able to fit in memory at once.

You can create your own iterators, by defining what is known as agenerator function. To illustrate the usefulness of this, let us start by considering a simple function to return theconcatenation of two lists:

defconcat(a,b):returna+bprint(concat([5,4,3],["a","b","c"]))# prints [5, 4, 3, 'a', 'b', 'c']

Imagine wanting to do something likeconcat(list(range(0, 1000000)), list(range(1000000, 2000000)))

That would work, but it would consume a lot of memory.

Consider an alternative definition, which takes two iterators as arguments:

defconcat(a,b):foriina:yieldiforiinb:yieldi

Notice the use of theyield statement, instead ofreturn. We can now use this something like

foriinconcat(range(0,1000000),range(1000000,2000000)):print(i)

and print out an awful lot of numbers, without using a lot of memory at all.

Note: You can still pass a list or other sequence type wherever Python expects an iterator (like to an argument of yourconcat function); this will still work, and makes it easy not to have to worry about the difference where you don’t need to.

Links:

External Links

[edit |edit source]
Previous: LoopsIndexNext: Scoping
Retrieved from "https://en.wikibooks.org/w/index.php?title=Python_Programming/Functions&oldid=4432017"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp