A function is like a little program that you can use to perform a specific action. Python has a lot of functions that can do many wonderful things. However, it may not always be the ideal function that you are looking for. At that time, you will need to create your own function so that it perform your own idea task accordingly.
So how do you define a function? A Python function using the def statement, providing a name for your function and specifying either an empty or populated argument list within parentheses. The standard form looks something like this
<your function code goes here>
A function start with the def statement. It then follow with a function name, well you can give it any name. Arguments lists are optional, but the parentheses are NOT. A colon (:) follows the closing parenthesis and indicates the start of your function code.
Let’s create your first Python function in the following example.
print "Hello World!"
>>> print Hello()
Hello World!
Let’s create another function which take 1 argument.
print "Hello, " + name
>>> Hello('John')
Hello, John
The following function will take 2 arguments. It add both value and return to the caller.
total = val1 + val2
return total
>>> print 'Total is %d' % GetTotal(10, 8)
Total is 18
Function arguments default value:
Python function allow you to set the default value for its arguments. In the following example, we set ‘nobody’ as a default value for name argument. When Hello() function is called without any argument, it print the default name value. On the other hand, when Hello() function is called with name argument provided, it will print the provided name value instead of the default value.print "Hello, " + name
>>> Hello()
Hello, Nobody
>>> Hello('John')
Hello, John
Passing list of arguments:
Sometimes, you may want to pass more than one arguments at a time to a function. For example, instead of calling the same function for multiple times, you can call the function once only with list of parameters. In the following example, the Colors function take a list of colors. It then loop through the tuple and print each of its element.for p in colors:
print "Color: " + p
>>> Colors('Red', 'Blue', 'Cyan', 'Green', 'Yellow', 'White')
Color: Red
Color: Blue
Color: Cyan
Color: Green
Color: Yellow
Color: White
Scoping:
Scoping is about how the variable work within a Python function. Take a look at the following example. x is a global variable which assigned to 10. The ChangeValue() function will re-assigned x to 5 and it then print the value x.>>> def ChangeValue():
x = 5
print 'x = %d' % (x)
10
>>> ChangeValue()
x = 5
>>> x
10
>>> def ChangeValue():
global x
x = 5
print 'x = %d' % (x)
10
>>> ChangeValue()
x = 5
>>> x
5
Python Tutorial: Functions