Defining Functions
We can create a function that writes the Fibonacci series to an arbitrary boundary:
The keyword def introduces a function definition. It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line, and must be indented.
A function definition associates the function name with the function object in the current symbol table. The interpreter recognizes the object pointed to by that name as a user-defined function. Other names can also point to that same function object and can also be used to access the function:
Return value.
It is simple to write a function that returns a list of the numbers of the Fibonacci series, instead of printing it:
This example, as usual, demonstrates some new Python features:
The
returnstatement returns with a value from a function.returnwithout an expression argument returnsNone. Falling off the end of a function also returnsNone.
The statement
result.append(a)calls a method of the list objectresult. A method is a function that ‘belongs’ to an object and is namedobj.methodname, whereobjis some object (this may be an expression), andmethodnameis the name of a method that is defined by the object’s type. Different types define different methods. Methods of different types may have the same name without causing ambiguity. (It is possible to define your own object types and methods, using classes, see Classes) The methodappend()shown in the example is defined for list objects; it adds a new element at the end of the list. In this example it is equivalent toresult = result + [a], but more efficient.
4.9.1. Default Argument Values
The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:
This function can be called in several ways:
giving only the mandatory argument:
ask_ok('Do you really want to quit?')giving one of the optional arguments:
ask_ok('OK to overwrite the file?', 2)or even giving all arguments:
ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')
This example also introduces the in keyword. This tests whether or not a sequence contains a certain value.
The default values are evaluated at the point of function definition in the defining scope, so that
will print 5.
Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:
This will print
If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:
fn('Placencio', 100, 300, 200, name='Ambiorix', lastname='Rodriguez')
https://docs.python.org/3/tutorial/controlflow.html#defining-functions
No hay comentarios:
Publicar un comentario