Fandom

Python Wiki

Functions

43pages on
this wiki
Add New Page
Talk0 Share

General informations Edit

Functions are some bunch of code. The advantage (and reason for creating them) of functions is the fact, that we can use them (and with this the specified code) everywhere in the program and in other Classes.

Syntax of functions Edit

To define a function, we use the keyword def. After this we write the function name and a : All code that belongs to this function now has to be indented, as Python does not feature braces.

A basic example (version 3.X):

>>> def hel():
...     print('Hello')
...
>>> hel()
'Hello'

Parameters Edit

The mechanism of parameter-passing in Python is a special theme. But this won't be discussed here, we just look at how we can pass them to functions:

>>> def HW(times):
...    if times < 0:
...        print('Cannot print')
...    elif times == 0:
...        print('Printed nothing')
...    else:
...        for index in range(terms):
...            print('Hello World!')
...
>>> HW(3)
Hello World!
Hello World!
Hello World!

Note that there can be multiple parameters and also two special things discussed below.

Variable number of parameters Edit

*args Edit

Sometimes it's useful that a function can handle a variable number of parameters. If your are familiar with C or C++, this is equivalent to the *varargs thing.

To make this available, we have to assing a paramter with an Asterisk, the common wildcard standing for anything:

>>> def some_func(*args):
...     print(args)
... 
>>> some_func(2)
(2,)
>>> some_func(2,3,5)
(2, 3, 5)

**kwargs Edit

Sometimes it's also useful to make a function handle several variable keyword arguments, an example:

>>> def print_keyword_args(**kwargs):
...     # kwargs is a dict of the keyword args passed to the function
...     for key, value in kwargs.iteritems():
...         print('%s = %s' % (key, value))
... 
>>> print_keyword_args(first_name="John", last_name="Doe")
first_name = John
last_name = Doe

A further advantage is that we can define how to use several parameters, but the function will also do the right thing if we pass this variable keyword parameter not.

The best explanation is the following example, taken from the Python tutorial:

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print "-- This parrot wouldn't", action,
    print "if you put", voltage, "volts through it."
    print "-- Lovely plumage, the", type
    print "-- It's", state, "!"
 
parrot(1000)                                         
parrot(voltage=1000)                                 
parrot(voltage=1000000, action='VOOOOOM')            
parrot(action='VOOOOOM', voltage=1000000)            
parrot('a million', 'bereft of life', 'jump')        
parrot('a thousand', state='pushing up the daisies')

Note: For the example above the voltage-parameter has to be passed everytime. So the following woule be invalid:

parrot()

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.