Python Functions

A function is like a small black box machine that does something.  Imagine a factory filled with little mini-factories.  One mini factory makes a Twinkie cake, one mini-factory makes the delicious Twinkie filling and third factory receives both of these items and combines them together and then returns the finished product.  It is sort of like that…

You must declare the function and what it receives from outside the function.   Then you perform stuff in the block code and finally return something to outside the function.

The 3 parts of a function are called:  name, block and return

Time to look at some examples and get rolling.  Use “def” to define a function and a colon at the end of the line.

Very Basic Function

def printMe():
    print("Well hello there!")

printMe()

The above function receives no parameters (stuff in the parenthesis) and is called by the “printMe()” which activates function.  The function prints out some text, but there is nothing returned and nothing stored – not especially useful.

 

Your Name – %

def nameMe(fname, lname):
    print('Hello %s %s' % (fname, lname))

nameMe("Albert", "Einstein")

This one is a good one because it shows you a simple function and a new thing… the %s.   %s is s place holder for whatever comes after in the parenthesis.  This can save work when changes are necessary.  This function is fairly simple.  It is named “nameMe”, it receives 2 parameters – “fname” and “lname” and it executes a block of code that is just one line.

 

Twinkie

Now take a look at the Twinkie factory below.

Please note that with regards to variables, (much like Vegas) what happens in the function stays in the function.  In the example below I used the variable “i” inside of both functions.  I could have used any variable name, but I wanted to show that the variable scope is limited to with in the function.  Outside the function the program does not know the value of “i.”

#twinkie factory

def cake_maker():
    i = "The delicious yellow cake!"
    return i

def filling_maker():
    i = "The tasty filling!"
    return i

part1 = cake_maker()
print("Part One: ", part1)

part2 = filling_maker()
print("Part Two: ", part2)

In the above example I defined two functions one cake_maker and one filling_maker.  They receive no inputs, but if they did it would go int the ().   The block of code defines the variable i and returns i to outside the function.

A tricky part of function sometimes is understanding what calls them to action.  In this case it is the “part1 = cake_maker()” line of code and the “part2 = filling_maker.”  Using a variable to capture the returned information is a common way of calling functions.

Essentially the code above is the factory and says go to the mini-factory called cake_maker and ask it for an output.  cake_maker returns the value of i, which is a string of text.  Then do the same for filling maker.  Now what was produced inside the function is usable outside the function.  It may seem silly on such a small scale, but for larger complex programs it helps to segregate problems and make editing easier.

 

Twinkie Factory Continued

#twinkie factory

def cake_maker():
    i = "The delicious yellow cake"
    return i

def filling_maker():
    i = "the tasty filling!"
    return i

part1 = cake_maker()
print("Part One: ", part1)

part2 = filling_maker()
print("Part Two: ", part2)

def assembler(stuff1, stuff2):
    twinkie = "Twinkie: " + stuff1 + " and " + stuff2
    return twinkie
print()
final_product = assembler(part1, part2)
print(final_product)

Now we added the “assembler” function.  This receives two parameters (fancy word for inputs) just like a factory might receive parts to work with and assemble things.  Once they have been received it uses the inputs (now called arguments for some reason) to complete the task it has been assigned to do.

The value of part1 becomes the value of stuff1
The value of part2 becomes the vale of stuff2
the value of twinkie becomes the value of final_product

 

Built in Functions

These are common functions that are ready for use by you.  No need to define them.  We have used print() quite a bit.  It is just another built in function.

Built-in Function Description
abs() Return the absolute value of a number.
all() Return True if all elements of the iterable are true (or if the iterable is empty).
any() Return True if any element of the iterable is true. If the iterable is empty, return False.
ascii() Return a string containing a printable representation of an object, but escape the non-ASCII characters.
bin() Convert an integer number to a binary string.
bool() Convert a value to a Boolean.
bytearray() Return a new array of bytes.
bytes() Return a new “bytes” object.
callable() Return True if the object argument appears callable, False if not.
chr() Return the string representing a character.
classmethod() Return a class method for the function.
compile() Compile the source into a code or AST object.
complex() Create a complex number or convert a string or number to a complex number.
delattr() Deletes the named attribute of an object.
dict() Create a new dictionary.
dir() Return the list of names in the current local scope.
divmod() Return a pair of numbers consisting of quotient and remainder when using integer division.
enumerate() Return an enumerate object.
eval() The argument is parsed and evaluated as a Python expression.
exec() Dynamic execution of Python code.
filter() Construct an iterator from elements of iterable for which function returns true.
float() Convert a string or a number to floating point.
format() Convert a value to a “formatted” representation.
frozenset() Return a new frozenset object.
getattr() Return the value of the named attribute of an object.
globals() Return a dictionary representing the current global symbol table.
hasattr() Return True if the name is one of the object’s attributes.
hash() Return the hash value of the object.
help() Invoke the built-in help system.
hex() Convert an integer number to a hexadecimal string.
id() Return the “identity” of an object.
input() Reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
int() Convert a number or string to an integer.
isinstance() Return True if the object argument is an instance.
issubclass() Return True if class is a subclass.
iter() Return an iterator object.
len() Return the length (the number of items) of an object.
list() Return a list.
locals() Update and return a dictionary representing the current local symbol table.
map() Return an iterator that applies function to every item of iterable, yielding the results.
max() Return the largest item in an iterable.
memoryview() Return a “memory view” object created from the given argument.
min() Return the smallest item in an iterable.
next() Retrieve the next item from the iterator.
object() Return a new featureless object.
oct() Convert an integer number to an octal string.
open() Open file and return a corresponding file object.
ord() Return an integer representing the Unicode.
pow() Return power raised to a number.
print() Print objects to the stream.
property() Return a property attribute.
range() Return an iterable sequence.
repr() Return a string containing a printable representation of an object.
reversed() Return a reverse iterator.
round() Return the rounded floating point value.
set() Return a new set object.
setattr() Assigns the value to the attribute.
slice() Return a slice object.
sorted() Return a new sorted list.
staticmethod() Return a static method for function.
str() Return a str version of object.
sum() Sums the items of an iterable from left to right and returns the total.
super() Return a proxy object that delegates method calls to a parent or sibling class.
tuple() Return a tuple
type() Return the type of an object.
vars() Return the __dict__ attribute for a module, class, instance, or any other object.
zip() Make an iterator that aggregates elements from each of the iterables.
__import__() This function is invoked by the import statement.

 

Functions are a vital part of programming you will see them in every language.  They allow large projects to be broken up into many smaller projects which can be allocated to small teams or individuals.

 

dir()

Here is a handy function… dir()  This returns the information about any value.  It tells you the functions that can be used with that value in alphabetical order.

>>>test_me = “I love Python!”
>>>dir(test_me)
returns a bunch of stuff… all functions related to strings.

Need help with all the options?  Just ask Python!
>>>help(test_me.upper)
returns details on the “upper” function

Great job on functions!  They can be a tough concept at first, but once you get it, they are very useful indeed!