# functions.py ''' A few basic examples regarding functions. ''' # # User defined functions. # def my_fun(a, b): ''' Does something. Always add some documentation. ''' a += 1 if a > 3: return a + b else: return a, b print('after return') myFun(4, 5) myFun? myFun?? x = 4 y = 5 print(my_fun(x, y)) print(x) # The scope of the variables is the function itself. # Functions can make use of global variables. x = 3 def my_fun(a, b): ''' Does something. Always add some documentation. ''' a += 1 return a + b + x print(my_fun(4, 5)) # Return more than one value. def my_fun(a, b): ''' Does something. Always add some documentation. ''' return a**2, abs(b) x, y = my_fun(2, -3) # my_fun returns a tuple. Its elements can be accessed like list elements. x = my_fun(2, -3)[0] y = my_fun(2, -3)[1] # # Recursion. # def factorial(n): ''' Computes the factorial. ''' if (type(n) != int) or (n < 0): print("error: input value invalid") return (-1) if (n == 0): return 1 else: return n*factorial(n-1) # # Argument values, keywords. # def my_fun(a, b, x=4, y=7): ''' A function with default arguments. ''' return (a + b)*x + y my_fun(2, 3) my_fun(2, 3, 1) my_fun(2, 3, x=1) my_fun(2, 3, y=1, x=1)