Those logic and operational commands are the main elements in constructing Functions. Now we systematically go through Function definition.
It take the form as starting from def, then name, in parenthis the parameters, followed by docstring to explain what this function is for. Then the while, if or for elements we went through.
Writing a function to calculate Fibonacci sequence:
>>> def fib(n): # write Fibonacci series up to n
… “””Print a Fibonacci series up to n.”””
… a, b = 0, 1
… while a >> # Now call the function we just defined:
… fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
Note instead of print the output, you can also write in the form ended with “return”
>>> def fib2(n): # return Fibonacci series up to n
… “””Return a list containing the Fibonacci series up to n.”””
… result = []
… a, b = 0, 1
… while a >> f100 = fib2(100) # call it
>>> f100 # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
In a typical function, you will define the parameters or arguments, Python allows a predefined arguments so you wont’ need to enter each one upon invoking it. for example,
def ask_ok(prompt, retries=4, reminder=’Please try again!’):
while True:
ok = input(prompt)
if ok in (‘y’, ‘ye’, ‘yes’):
return True
if ok in (‘n’, ‘no’, ‘nop’, ‘nope’):
return False
retries = retries – 1
if retries < 0:
raise ValueError('invalid user response')
print(reminder)
There is additional useful caveats about how to unpack argument list using asterisk for list, tuple and double asterisk for dictionary. (examples in modules.py)
Learning functions inevitably needs to know anonymous function or lambda too. Lambda is more or so a syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope. The following shows a formal function and an anonymous/lambda function.
>>> def make_incrementor(n):
… return lambda x: x + n
…
>>> f = make_incrementor(42)
Finally, one needs to write docstring and annotations for functions. docstring is straightforward, while annotations,
4. More Control Flow Tools
Annotations are stored in the __annotations__ attribute of the function as a dictionary and have no effect on any other part of the function. Parameter annotations are defined by a colon after the parameter name, followed by an expression evaluating to the value of the annotation. Return annotations are defined by a literal ->, followed by an expression, between the parameter list and the colon denoting the end of the def statement. The following example has a positional argument, a keyword argument, and the return value annotated:
def f(ham: str, eggs: str = ‘eggs’) -> str:
print(“Annotations:”, f.__annotations__)
print(“Arguments:”, ham, eggs)
return ham + ‘ and ‘ + eggs