Basic Python functions
|
A function is a way of tying a bunch of code together so that it can be used at a later time. To create a function, it must be defined with the def command.
>>> def example(): print 'I am a seemingly self aware function!'
This assigns the name 'example' in the same way that the statement 'x = 1' assigns the name x to the value 1. Merely typing the name of the function will show you such.
>>> example <function example at 0x01680730>
To actually call the function, you have to include parenthesis afterwards.
>>> example() I am a seemingly self aware function!
The reason for the parenthesis is so that you can pass arguments to functions that require them.
>>> def square(x): print x**2 >>> square(4) 16
If we wanted to use the value that the square function gives us, we would rewrite it make use of the return command.
>>> def square(x): return x**2
Which can then be used to do such fun things as:
>>> print square(3) 9
or
>>> print square(square(3)) 81
or even in statements such as:
>>> 10 + square(2) 14
and
>>> y = square(10) >>> y 100
[edit] See also
|