Python Forum
[Basic] Functions - Printable Version

+- Python Forum (
+-- Forum: General (
+--- Forum: Tutorials (
+---- Forum: Fundamentals (
+---- Thread: [Basic] Functions (/thread-328.html)

Functions - metulburr - Oct-05-2016

Why use functions?
  • They maximize code reuse and minimize redunancy
    • Package logic when using in more than one place and more than one timeReduce maintenance. For example, if you need to fix something, it gets fixed once in the function and not the 10+ times the function is called
  • Procedural decomposition
    • Split systems into pieces that have well-defined roles

Function design concepts
  • coupling: use arguments for inputs and return for outputs
  • global variables are a poor way for functions to communicate
  • don't change mutable arguments unless the caller expects it, avoid specific function
  • each function should do ONE thing.

Coding functions
They are called in expressions, are passed values, and return results.
  • def
    • def is executable code. Your function does not exist until Python reaches and runs def. def creates a function object and assigns it to a name
  • lambda
    • lambda create an object but returns it as a result. It allows in-line function definitions. It is an expression not a statement, un-like def
  • return
    • return sends a result object back to the caller. When a function is called, the caller stops until the function finishes its work and returns control to the caller. Functions that compute a value send it back to the caller with a return statement. The returned value becomes the the result of the function call.The return statement can show up anywhere in the function's body, it ends the function call and sends a result back to the caller
  • yield
    • yield sends a result object back to the caller, but remembers where it left off. Functions known as generators, also use the yield statement to send back a value and suspend their state, to be resumed later, to produce a series of results over time
  • global
    • global declares module-level variables that are to be assigned.
  • nonlocal
    • nonlocal declares enclosing function variables that are to be assigned
  • Arguments
    • Arguements are passed by assignment (object reference).

Function general format
def add(arg1, arg2):
	value = arg1 + arg2
	return value
So this is a small basic example of a function. It does one thing, adds its arguments. Executing this code snippet will do nothing. This function needs to be called to execute. Let's dissect this definition a little bit more. The def is a keyword, which starts the creation of a function object and it assigns it the name add. This name is made by you. The arguments names in the header are assigned to the objects passed in parenthesis at the point of call.  The two indented lines are the functions body. This gets executed every time the function is called.

The variable value is a local variable only known in the function call(). The last line in the body of the function, returns the value of the local variable to the caller.
val = add(5,2)

This is the call of the function. The first calls the function and assigns the value to the variable val. Then is prints that variable. The second prints the result of the fiunction call directly.
So after making this call:
val = add(5,2)
you are essentially doing:
val = 7
because 7 was returned to the caller. So the section of code add(5,7) gets "replaced" with the value 7.

Functions without return statements
When the return statment is non-existant, the function exits when the control flow falls off the end of the function body. Every function returns something. If you do not have a return statement, the function returns the value None automatically.
def add(arg1, arg2):
	value = arg1 + arg2
This snippet of code will print the results:
The 6 is printed because of the print inside the function's body. The None is printed because we are printing the functions return value. Since we did not return anything, it returns None.

def executes at runtime
def is an executable statement. Because of that, it can appear anywhere a statment can, even nested in other statements. An example would be:
if test:
	def func():
	def func():
So based on the if condition, func() can be defined differently. 

Because definition happens at runtime, there is nothing special about the function name. What is important is the object to which it refers:
def func(func_name):
	print('in body of function {}'.format(func_name))


othername = func
in body of function func
in body of function othername
Recursive functions
Functions that call themselves either directly or indirectly in order to loop is recursion.
def recursive(string, num=0):
	print('{} {}'.format(string, num))
	recursive(string, num + 1)

test 0
test 1
test 2
test 3
test 4
test 5
test 6
test 7
test 994
test 995
test 996
Traceback (most recent call last):
  File "", line 8, in <module>
  File "", line 6, in recursive
    recursive(string, num + 1)
    print('{} {}'.format(string, num))
RuntimeError: maximum recursion depth exceeded while calling a Python object