Page 199 - Data Science Algorithms in a Week
P. 199
Python Reference
Functions
Python supports the definition of the functions which is a good way to define a piece of
code that is executed at multiple places in the program. A function is defined using the
keyword def.
Input:
source_code/appendix_c_python/example13_function.py
def rectangle_perimeter(a, b):
return 2 * (a + b)
print 'Let a rectangle have its sides 2 and 3 units long.'
print 'Then its perimeter is', rectangle_perimeter(2, 3), 'units.'
print 'Let a rectangle have its sides 4 and 5 units long.'
print 'Then its perimeter is', rectangle_perimeter(4, 5), 'units.'
Output:
$ python example13_function.py
Let a rectangle have its sides 2 and 3 units long.
Then its perimeter is 10 units.
Let a rectangle have its sides 4 and 5 units long.
Then its perimeter is 18 units.
Program arguments
A program can be passed arguments from the command line.
Input:
source_code/appendix_c_python/example14_arguments.py
#Import the system library in order to use the argument list.
import sys
print 'The number of the arguments given is', len(sys.argv),'arguments.'
print 'The argument list is ', sys.argv, '.'
Output:
$ python example14_arguments.py arg1 110
The number of the arguments given is 3 arguments.
The argument list is ['example14_arguments.py', 'arg1', '110'] .
[ 187 ]