def Keyword
This page was last reviewed on Mar 22, 2024.
Dot Net Perls
Def. 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.
Def and return. 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.
However The method returns the result of the division expression in every other case.
Note This method receives arguments and returns explicit values. It is possible for a 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
Pass. 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()
Default. 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.
Argument 1 Width is set to 10 when no first argument or named argument is passed to computesize.
Argument 2 Height is by default set to 2. We can specify just the height using a named argument, as in the third computesize call.
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
One line. 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")
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.
Note With recursion, we solve search problems. For example, we can determine all possible ways to count change.
Note 2 If a recursive method calls itself in only one spot, it can be rewritten to instead use iteration.
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 argument. A 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.
Tip The tuple in this program, of identifier t, can be used in the same way as any 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 argument. Some 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.
And In the method body, we use that parameter as a dictionary. It uses standard dictionary syntax.
Tip The dictionary parameter, specified with this syntax, comes last in the formal parameter list.
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
Callable. 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
Benchmark, inline methods. 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.
Version 1 In this version of the code, method1 returns the results of three sub-methods. The methods are separate in the source code.
Version 2 Method1b directly does the computations. It contains the same logic as version 1.
Result Inlining can make code harder to read (or, sometimes, easier to read). It reduces method call overhead.
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
Notes, return. 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).
Lambda. 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.
Warning For complex methods, or ones that are called in many places, a def-method is often better than a lambda expression.
Timeit. 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.
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 22, 2024 (edit).
© 2007-2024 Sam Allen.