Functions

Functions are an integral part of any Python program, helping piece together all of the operations in a readable and non-redundant manner.

Arguably, redunancy is the primary reason for functions to exist. Programs can be built with all of the code in a line, with no functions whatsoever, but these sorts of programs are difficult to write, difficult to read, and difficult to modify.

It is for this reason that even the most basic of languages contain functions: for when the same thing needs to be done more than one time.

Here is a basic function definition which does nothing:

def nothing():
	return

From this, we can add operations to our function:

def printwords():
	print("words")

Or parameters, which are variables provided to the function when it is called:

def printwords(words):
	print(words)

A function can be run by calling it with its name, followed by (), with function parameters inside the parentheses.

printwords("words")
"words"

These are functions which don't return any values from them; by adding return within a function followed by a value, a function will evaluate to a value when it is called:

def one_arg_one_ret(num):
   x = num + num
   return (x, x+x)

When run, this function will return a tuple containing twice the number provided in the arguments list, and that number twice itself.

integer = 10
val = one_arg_one_ret(integer)
print(val)
(20, 40)

Whether or not a variable passed to a function is directly modifiable within the function, or simply a copy of the variable passed to the function, depends on the type of data the variable is.

def change_str(var):
   var = var + "end"

string = "the "
change_str(string)

If we now check the string variable, it will still contain "the ".

def change_list(var):
   var = var.append("end")

str_list = ["the "]
change_list(str_list)

If we check the str_list variable after calling change_list, it will contain ["the ", "end"], despite the variable not explicitly being changed.

If this seems confusing, that's because it is. There is a document called The Zen of Python which has some wisdom for us.

Explicit is better than implicit.
Simple is better than complex.

Generally, it is good practice to avoid functions which implicitly modify variables outside of the scope of the actual function.