A Comprehensive Introduction to Python Programming and ... - MSDL
A Comprehensive Introduction to Python Programming and ... - MSDL
A Comprehensive Introduction to Python Programming and ... - MSDL
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
1.2 Language Features 13 / 75<br />
1.2.6 Function Definitions <strong>and</strong> Function Calls<br />
Function in <strong>Python</strong> are declared using the def keyword. The basic syntax is as follows:<br />
def func name(arg1, arg2, . . ., argN):<br />
statements<br />
Listing 14: Functions<br />
Since the language is untyped, no function definition has a return type, <strong>and</strong> parameters<br />
are simply listed. If a function is <strong>to</strong> return a value, the keyword return can be<br />
used <strong>to</strong> return it. The same keyword used without a value will s<strong>to</strong>p the excution of the<br />
function. This also the convention that C <strong>and</strong> Java use.<br />
<strong>Python</strong> also supports some interesting features relative <strong>to</strong> function calls. The first of<br />
these features is that arguments can be passed <strong>and</strong> filled in two distinct ways: the traditional<br />
(ie C <strong>and</strong> Java) way, which is by position. Alternatively, <strong>Python</strong> supports filling<br />
in arguments by name. When arguments are provided by name, then their placement in<br />
the argument list does not matter, since the name has precedence over the place in the<br />
list. To make this concept clearer, here are two examples illustrating the two methods<br />
previously described:<br />
Listing 15: Arguments Example 1 - filled in by position<br />
>> def foo(w, x, y, z):<br />
return (w, x, y, z)<br />
>> foo(1, 2, 3, 4)<br />
(1, 2, 3, 4)<br />
>> 5<br />
Listing 16: Arguments Example 2 - filled in by name<br />
>> def foo(w, x, y, z):<br />
return (w, x, y, z)<br />
>> foo(x = 2, z = 4, w = 1, y = 3)<br />
(1, 2, 3, 4)<br />
>> 5<br />
It is also possible <strong>to</strong> combine the two methods in the same function call, provided<br />
that all arguments following the first one that is passed by name are also passed by<br />
name. The arguments before the first one that is passed by name will all be passed by<br />
position.<br />
Note that multiple definitions of a single argument will raise an exception. An<br />
exception is also raised if not all arguments receive a value, the arguments that are<br />
ignored have been assigned a default value, as explained next.