3.1 define a function
Functions start with the keyword def
followed by the name of the function and the parenthesis (which hold arguments), the :
sets the beginning of the scope of the function.
# define a function def func1(): print "I am a function" func1() print func1() print func1
func1()
calls the function which prints "I am a function". OK.
print func1()
calls func1()
which prints "I am a function", that is followed by "none" because after func1()
runs it doesn't return a value, when python tried to print func1()
the result is "none." Claro? Si Claro!
print func1
prints a pointer to the address in memory of the function object.
3.2 function that takes arguments
# function that takes arguments def func2(arg1, arg2): print arg1, " ", arg2 func2(10,20) print func2(10,20)
Notice no +
signs are necessary when appending strings using the print method.
As you would expect func2(10,20)
prints 10 20
to output and print func2(10,20)
prints 10 20 none
to output. As above there is no return value of func2
so printing it returns "none".
3.3 function that returns a value
# function that returns a value def cube(x): return x*x*x print cube(3)
Unlike the above examples print cube(3)
prints the value 27 to output because we have asked the function to return
a value.
3.4 function with default value for an argument
# function with default value for an argument def power(num, x=1): result = 1; for i in range(x): result = result * num return result print power(2) # a default x is defined print power(2,3) # defaults are over-ridden by supplied args print power(x=3, num=2) # order is not important if args are named
This behaves exactly as you would expect. Note the order of the arguments, when you call the function, doesn't matter if the arguments are named.
3.5 function with variable number of arguments
# function with variable number of arguments def multi_add(*args): result = 0; for x in args: result = result + x return result print multi_add(4,5,10,4)
Here the asterisk means you are going to pass-in an undefined number (some arbitrary number) of arguments. Very nice...