General information[]
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 otherClasses.
Syntax of functions[]
To define a function, we use the keyworddef. After this we write the function name and a : All code that belongs to this function now has to beindented, as Python does not feature braces.
A basic example (version 3.X):
>>>defhel():...print('Hello')...>>>hel()'Hello'
Parameters[]
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:
>>>defHW(times):...iftimes<0:...print('Cannot print')...eliftimes==0:...print('Printed nothing')...else:...forindexinrange(terms):...print('Hello World!')...>>>HW(3)HelloWorld!HelloWorld!HelloWorld!
Note that there can be multiple parameters and also two special things discussed below.
Variable number of parameters[]
*args[]
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 foranything:
>>>defsome_func(*args):...print(args)...>>>some_func(2)(2,)>>>some_func(2,3,5)(2,3,5)
**kwargs[]
Sometimes it's also useful to make a function handle several variable keyword arguments, an example:
>>>defprint_keyword_args(**kwargs):...# kwargs is a dict of the keyword args passed to the function...forkey,valueinkwargs.iteritems():...print('%s =%s'%(key,value))...>>>print_keyword_args(first_name="John",last_name="Doe")first_name=Johnlast_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:
defparrot(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",typeprint"-- 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 thevoltage-parameterhas to be passed everytime. So the following woule be invalid:
parrot()
