In Python programs we use the def
-keyword to create functions. Statements may be top-level. But it is possible to structure logic into methods.
In a function, we can place a "return" statement to return a value. A tuple can be used to return multiple values at once.
We use def
for a simple "dividesafe" method that receives 2 arguments. In its body, it checks the argument "b" against zero. It returns -1 if the division would cause an error.
def
-method in Python to return no value.def dividesafe(a, b):
# Handle zero denominator.
if b == 0:
return -1
# Divide.
return a / b
# Use method.
print(dividesafe(10, 5))
print(dividesafe(10, 0))2.0
-1
It is possible to create an empty method, one with no return value. In methods that return no value, a return statement is not required. In this case we can use a pass statement.
def waste_of_time():
# This method does nothing.
pass
# Call empty method.
waste_of_time()
Method arguments can optionally have default values. These defaults are used when no argument is passed to the method. Here, we show a method that has 2 default-valued arguments.
def computesize(width=10, height=2):
return width * height
print(computesize()) # 10, 2: defaults used.
print(computesize(5)) # 5, 2: default height.
print(computesize(height=3)) # 10, 3: default width.20
10
30
We can specify small methods on one line. For short
methods, like ones that call other methods (such as print) this syntax is convenient.
# Print uppercased form of the string.
def printupper(s): print(s.upper())
printupper("hello")
printupper("world")HELLO
WORLD
In recursion, a method calls itself. This helps solve complex problems. This next program solves no problems. Instead it demonstrates recursion. It ceases once its argument exceeds 10.
def recursive(depth):
# Stop recursion if depth exceeds 10.
if depth > 10:
return
print(depth)
# Call itself.
recursive(depth + 1)
# Begin.
recursive(5)5
6
7
8
9
10
Tuple
argumentA method in Python can receive any number of arguments stored in a tuple. This requires the single-star syntax. A formal parameter of name *t can be used as a tuple.
def display(*t): # Print tuple. print(t) # Loop over tuple items. for item in t: print(item) # Pass parameters. display("San Francisco", "Los Angeles", "Sacramento") display(2, 0, 1, 4)('San Francisco', 'Los Angeles', 'Sacramento') San Francisco Los Angeles Sacramento (2, 0, 1, 4) 2 0 1 4
Dictionary
argumentSome parameter types have special syntax. A method can receive a dictionary of keys and values. This is specified with two stars before the parameter name.
def display(**values): # Loop over dictionary. for key in values: print(key, "=", values[key]) # Newline. print() # Pass named parameters. display(first = "Sigmund", last = "Freud", year = 1899) display(one = 1, two = 2)year = 1899 last = Freud first = Sigmund two = 2 one = 1
This built-in is not often useful, but I include it for completeness. We can tell if an object (like an integer or lambda) can be called with it.
method = lambda n: n == 2 # A method is callable. if callable(method): print(True) number = 8 # An integer is not callable. if not callable(number): print(False)True False
There is a cost to calling a method. We can reduce this by inlining or combining methods. This can be done by pasting several method bodies together.
import time # Method that calls other methods. def method1(v): return method2(v) + method3(v) + method4(v) def method2(v): return v + 2 def method3(v): return v + 3 def method4(v): return v + 4 # Method with all computations inlined. def method1b(v): return v + 2 + v + 3 + v + 4 # Test them. print(method1(5)) print(method1b(5)) print(time.time()) # Version 1: non-inlined methods. i = 0 x = 0 while i < 1000000: x = method1(5) i += 1 print(time.time()) # Version 2: inlined methods. i = 0 while i < 1000000: x = method1b(5) i += 1 print(time.time())24 24 1405711521.510698 1405711522.499755 method1 = 0.989 s 1405711523.037786 method1b = 0.538 s
We can do more than just return 1 number in Python. We can return a tuple, which contains more than 1 value. Or we can return None
(like a void
method).
Often a method has a single statement. The lambda expression syntax, with the keyword "lambda," is helpful here. It makes programs easier to write and shorter.
def
-method is often better than a lambda expression.Statements and methods can be benchmarked. You can use simple calls to time()
, or the more complex timeit
module. Micro-benchmarks tend to waste a lot of time.
With def
, a function syntax form, we add further levels of structure to our programs. This yields programs that are clearer, smaller and often faster than unstructured designs.