Tuesday, 15 January 2013

Python Language Lesson: function


Python Language Lesson: function

Functions are a way to divide your code into independent tasks. A
function has a name and a body and it may be called. Optionally, a
function may take input variables, which are called parameters, and it
may return an output value. Here is an example:
def add values(x, y):
print "Values are", x, y
return x + y
The keyword def starts the function definition. After the keyword
def comes the function name, in this case add values. In parentheses,
follow the function parameters separated by commas. A colon
ends the function header.
The indented lines below the function header form the function
body, which is executed line by line when the function is called. In
Python, indentation makes a difference, so make sure that the lines
are aligned correctly in the function body. Function bodies follow the
same indentation rules as if clauses and loops. The function body may
contain a return statement followed by a value which is returned to
the calling line. The return statement is optional.
A function is called with the function name followed by the input
values in parentheses:
z = 3
new sum = add values(z, 5)
print "Their sum is", new sum
If no input values are given, there is nothing between the parentheses.
The return value may be assigned to a variable, for example
new sum = add values(z, 5), or the function call may be included
in a more complex expression. For example, the code of the last line
in the example above could have read:
print "Their sum is", add values(z, 5)
In this case, you would not need the new sum variable in the
example above. As you might guess, the example produces this output:
Values are 3 5
Their sum is 8

No comments:

Post a Comment