C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
Python program that uses def
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))
Output
2.0
-1
Python program that uses pass statement
def waste_of_time():
# This method does nothing.
pass
# Call empty method.
waste_of_time()
Width: This is set to 10 when no first argument or named argument is passed to the computesize method.
Height: This is by default set to 2. We can specify just the height using a named argument, as in the third computesize call.
Python program that uses default 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.
Output
20
10
30
Python program that uses one-line def
# Print uppercased form of the string.
def printupper(s): print(s.upper())
printupper("hello")
printupper("world")
Output
HELLO
WORLD
Note: With recursion, we solve search problems. For example, we can determine all possible ways to count change.
RecursionNote 2: If a recursive method calls itself in only one spot, it can be rewritten to instead use iteration.
WhilePython program that uses recursion
def recursive(depth):
# Stop recursion if depth exceeds 10.
if depth > 10:
return
print(depth)
# Call itself.
recursive(depth + 1)
# Begin.
recursive(5)
Output
5
6
7
8
9
10
Tip: The tuple in this program, of identifier t, can be used in the same way as any tuple.
Python program that receives tuple argument
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)
Output
('San Francisco', 'Los Angeles', 'Sacramento')
San Francisco
Los Angeles
Sacramento
(2, 0, 1, 4)
2
0
1
4
And: In the method body, we use that parameter as a dictionary. It uses standard dictionary syntax.
DictionaryTip: The dictionary parameter, specified with this syntax, comes last in the formal parameter list.
Python program that receives dictionary argument
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)
Output
year = 1899
last = Freud
first = Sigmund
two = 2
one = 1
Python program that uses callable
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)
Output
True
False
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.
Python program that times methods, inlined computations
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())
Output
24
24
1405711521.510698
1405711522.499755 method1 = 0.989 s
1405711523.037786 method1b = 0.538 s
Caution: For complex methods, or ones that are called in many places, a def-method is often better than a lambda expression.
Lambda