Formulated by Andy Hunt and Dave Thomas in "The Pragmatic Programmer"
Steve Smith in [Henney (2010), p. 60f]
A function gives a name to a block of code
The named block of code can be executed by "calling" the function name
Function names should state what the function does or what it returns
When using appropriate function names, code becomes easier to read
# ...delta_x, delta_y are defined, `sqrt` is available
delta_x2 = delta_x * delta_x
delta_y2 = delta_y * delta_y
distance = sqrt(delta_x2 + delta_y2)
# vs. (requires `hypot` function to be available)
distance = hypot(delta_x, delta_y)
()
after a function name calls (executes) that
function
(.)
indicates that a function expects one or more
arguments
"""..."""
__doc__
attributedef <funcname>(parameter1, parameter2, ..., parameterN) [-> annotation]:
"""
Textual explanation of what the function is supposed to do.
"""
<suite>
#!/usr/bin/env python3
def interest(capital, rate, years=1):
"""
Return the total interest of investing `capital` at `rate`.
"""
value = capital * (1 + rate) ** years
return value - capital
print(interest(100, 0.03))
result = interest(100, 0.03, 3)
profit = interest(1300, 0.025, 5)
Python passes references to objects
No need to worry when passing immutable objects
#!/usr/bin/env python3
def print_uppercase(text):
"""
Print the passed text as upper case.
"""
print(text.upper())
a_text = "Programming is fun!"
result = print_uppercase(a_text)
def print_sorted_list(l):
l.sort()
print(l)
a_list = [5, 3, 7, 1, 4]
another_result = print_sorted_list(a_list)
It is possible to define default values for parameters
Default parameters can be omitted when passing arguments to a function
#!/usr/bin/env python
def power(base, exp=2):
return base ** exp
power(3, 3) # -> 27
power(5) # -> 25
Arguments may be passed matching the parameters' position or name
#!/usr/bin/env python3
def interest(capital=1000, rate=0.04, years=1):
"""
Return the total interest of investing `capital` at `rate`.
"""
value = capital * (1 + rate) ** years
return value - capital
print(interest(100, 0.03))
profit = interest(capital=1300, rate=0.025, years=5)
profit = interest(rate=0.03, years=3, capital=1200)
profit = interest(years=5)
profit = interest(1300, years=5)
result = interest(1000 + interest(rate=0.06), 0.03, 3)
ifmain
PatternDefine functions before using them
main(.)
functionifmain
pattern at the end of the file to call the
main
functionif __name__ == "__main__":
sys.exit(main())
sys.exit(main())
passes main's return value to the shell
0
means success, everything else means failure
Function associated with an object's data
a_string = 'Python'
a_string.upper()
min(3, 4, 2)
text = 'a,b,c'
text.split(',')
Common syntax for invoking multiple function respectively method calls
sin(sqrt(12))
text.upper().split()
Python supports lambda (anonymous or unnamed) functions
lambda [parameter_list]: expression
They behave like a function object defined with:
def <identifier>(parameter_list):
return expression
Lambda functions are expressions that can be created at their point of use
They are limited in comparison to regular functions (only a single expression)
Lambda functions are useful as arguments, e.g. for sorting.
#!/usr/bin/env python3
a_list = [3, 4, 19, 11, 1, 4, 6, 8, 5, 2, 0, 12, 13, 3]
a_list.sort(key=lambda x: x % 3) # sort by remainder of division by 3
print(a_list)
Having enough eyes, all bugs seem shallow.- Linus Torvalds