^^Function. Python.

def fibonacci(N):  # returns a a list of the first N Fibonacci numbers

    L = []
    a, b = 0, 1
    while len(L) < N:
        a, b = b, a + b
        L.append(a)
    return L

Functions can return any object

multiple return values are put in a tuple (indicated by commas)

def op(a,b):

    return a+b, a-b, a*b, a/b     #equi: return (a+b, a-b, a*b, a/b)

 

  1. op(3,2)    >>> (5, 1, 6, 1.5)
  2. apb, amb, axb, adb = op(3,2)   # assegna retval separatamente
  3. optuple = op(3,2)

geeksforgeeks/multiple-return-values-in-python

Default Argument Values; arguments optional in the call

def fibonacci(N, a=0, b=1):
    L = []
    while len(L) < N:
        a, b = b, a + b
        L.append(a)
    return L

the function can be called w/o the default argument

geeksforgeeks/default-arguments-in-python

In a function:

ref: python/tutorial/controlflow#defining-functions

c: E' una scelta intelligente, coerente con la creazione automatica delle variabili assegnate, senza necessita' di dichiarazione. Le variabili create automaticamente in una funzione, che visibilita' dovrebbero avere? Sono automaticamente considerate locali ! E' una scelta prudenziale, che evita la modifica involontaria di variabili globali.

Arguments are passed using  call by object reference

is passed an object reference, not the value of the object. If a mutable object is passed, the caller will see any changes the callee makes to it.

Returned value from function. return cmd.

everything is an object

 functions are objects

  functions can be passed as arguments to functions.

Inner function  (nested functions, enclosed funtion)

realpython/inner-functions-what-are-they-good-for

Anonymous (lambda) Functions

add = lambda x, y: x + y
add(1, 2)    >>> 3

 

pow2 = lambda x: x*x

pow2(5)    >>> 25

Factory function

def generate_esp_b(b):    # espondenziale in base b
    def nth_power(n):        # Define the inner function ...
        return b ** n

    return nth_power          # ... that is returned by the factory function.

 

espb2 = generate_esp_b(2)

espb2(8)    >>> 256

Links

WhirlwindTourOfPython/08-Defining-Functions.ipynb