Functions and Procedures in Python - Python

Functions and procedures are blocks of code that you can access from several different parts of your code. As you already know, Python gives you some built-in functions, but you can also create your own functions. Yours are called user-defined functions. Functions and procedures provide better modularity for your application and a high degree of code reusing.

Procedures are functions that don't return a value. The only difference between a function and a procedure is that a procedure has either a return command without arguments (that returns None), or it doesn't have any return statement. From now on, I will use only the word function.

While functions are being executed, they create their own namespace. Every time you invoke a function, such as function (a,b,c) lPython does a search within its namespaces looking for function to identify whether this is a python object.

lPython creates a tuple of the arguments that were passed. Following our example, we have arguments=(a,b,c).
lPython invokes the function internally like this: apply( function,arguments).

As you can see, tuples are an unavoidable concept inside the language. Python, by nature, allows introspection to an unprecedented degree. You can separate a function name from its parameters, store them in some place, play around with them, and later use the apply built-in function to execute the function.

Functions

Functions always start with the abbreviation def. Their end is defined by the last line of the indented block of code that goes underneath.

The general format of a function is as follows:

Remember that to call a function without arguments, it's necessary to use empty parentheses.

Python uses dynamic namespaces. In order to show that, the next example uses the value of n, available at the time of calling the function, because n isn't defined inside the function nor is it part of its list of arguments. nis part of the global namespace of the function.

>>>defadd_to_n(arg):
… return n + arg

Variables that have values assigned to them inside a function always belong to the function namespace. Study the next example to learn how to change a global variable inside a function by using the keyword global.

Python implements procedural abstraction. Although this topic has a scary name, it is something very easy and simple. Python offers this feature by providing anonymous functions implemented with the keyword lambda. This type of abstraction can be used when the function is just an expression. In other words, lambdais just another way of writing def, except that it doesn't have to be named, and you can only put an expression in it. (The return is implicit.) It is intended to be just a shorthand to write small functions

easier as shown in the following:

>>> f = lambda x: x * 2
>>>f(20)
40

The previous case can also be written as follows:

Here's another example:

Note that in this last example, it is necessary to pass the default arguments to the lambda function because Python has only local and global namespaces. lambdais very useful for functions—such as map, filter, and reduce—that need a function as an argument.

Parameters

All parameters (arguments) in the Python language are passed by reference. Modules, classes, instances, and other functions can be used as arguments to functions and examined dynamically. Keep in mind that you don't need to specify the object type of an argument. By default, arguments have a positional behavior, and you need to inform them in the same order that they were defined.

Whenever mutable objects (dictionaries and lists)—that are transported to a function as arguments—change within the function, their external values also change.

Python also offers you named arguments. This type is different from positional arguments because it enables you to call a function and pass argument names and values in an arbitrary way—the order isn't important at all. Both function calls

>>>connect(port=80, name="www.bebemania.com.br")
and
>>>connect(name="www.bebemania.com.br", port=80)

are executed perfectly well and in the same way (when the function is implemented, of course). Default arguments are also allowed by the syntax. If the argument isn't provided, the default value takes place. The default value is optional. Even though its absence doesn't break your program, its presence cuts many lines from your code, as shown in the following:

>>>def connect(port=80):

The following example demonstrates namespace handling along with default arguments:

This effect is because the value of a was collected when the function was created. In some cases, you cannot pre-identify the number of arguments that you might need. For this kind of situation, you can use the special symbols * and ** next to a generic argument name. *argsgets a tuple of values in the received order; **argsgets a dictionary mapping argumentname:value.

Returning Values

The return expression halts the execution of a function, but when it's followed by an expression, it returns the expression.

It is also possible for a function to have no return at all. When that happens, the value Noneis returned.

Built-In Methods

When you have a function f, the following built-in methods can be accessed:

Let's get the documentation string of the join function, which is part of the string module.

>>> import string
>>> print string.join.__doc__
join(list [,sep]) -> string
joinfields(list [,sep]) -> string

Return a string composed of the words in list, with intervening occurences of sep. Sep defaults to a single space. (join and joinfields are synonymous)

Dynamic Namespace

Maybe you haven't noticed yet, but Python uses dynamic namespace concepts. Each function, module, and class defines its own namespace when it is created. When you inform an instruction, command, or statement to Python, it searches first inside the local namespace and afterwards inside the global namespace.

Python has the following namespaces:

Built-in names— int, string, def, print, and so on Global names— Declared as global and assigned at the top-level of a module Local names— Assigned inside a function

When you are writing your code, you have two forms of writing an object name. You can use qualified names and unqualified names. Qualified names use object namespaces as references, for example:

>>> print objectnamespace.objectname

Unqualified names deal with scopes, provided the object is in your namespace. For example

>>> print objectname

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Python Topics