Pages

Sunday, April 4, 2010

The return statement


The return statement is used to return from a function i.e. break out of the function. We can optionally
return a value from the function as well.

Using the literal statement
Example 7.7. Using the literal statement
#!/usr/bin/python
# Filename: func_return.py
def maximum(x, y):
if x > y:
return x
else:
return y
print maximum(2, 3)
Output
$ python func_return.py
3
How It Works
The maximum function returns the maximum of the parameters, in this case the numbers supplied to the
function. It uses a simple if..else statement to find the greater value and then returns that value.
Note that a return statement without a value is equivalent to return None. None is a special type
in Python that represents nothingness. For example, it is used to indicate that a variable has no value if it
has a value of None.
Every function implicitly contains a return None statement at the end unless you have written your
own return statement. You can see this by running print someFunction() where the function
someFunction does not use the return statement such as:
def someFunction():
pass
The pass statement is used in Python to indicate an empty block of statements.

No comments:

Post a Comment