Monday, October 21, 2013

Python Intro Part Deux

Salutations!  If you're a returning reader, it's certainly nice to have you back.  If not, welcome!  You may want to look over the first portion of this tutorial.  This second portion will primarily cover Python function definitions.
A "function machine"
Functions are groups of instructions.  An example of a function in Plain English (tm) is "for each given value, double it".  The mathematical equivalent of this phrase is y = 2x.  In programming, we can define functions to do much more than simple math, but function notation in programming is based on mathematical notation so it is useful to reflect on this temporarily.  Now, let's get you defining some functions!

In Python, functions are defined by using the def keyword.  Here's an example of a simple function:
def double(n):
    return n * 2

double(5) returns 10

The above code saves the argument to the variable n and returns (spits out) n doubled.  So calling double(10) would spit out 20.  Functions can do more than math, however.  We can pass strings (a chain of characters) to functions and output data based on their values.  For example, let's define a greeting function:



def greet_user(username):
    print "Hello " + username + "!"
Let's try calling that function with a name:

greet_user("Max")

The above code will print Hello Max! to the console.  We can call functions with variables as well, not just with literals:
def chastise_child(childname):
    print "Stop that " + childname + "!"
first_child_name = "Freddy Mac"
second_child_name = "Fannie Mae"
third_child_name = "Barack"
chastise_child(second_child_name)
chastise_child(third_child_name)


The handy thing about functions is that you don't have to retype code every time you want to perform a similar action.  You might want to perform a complex operation on many different input values, and now you can with functions!

You can also define functions that take more than one input:
def multiply(first, second):
    return first * second
print multiply(5,10)
Inputs are separated by commas.  When passing values to a function with many parameters, order matters!  Consider this scenario:
def childinfo(name, eyecolor, age):
    return name+" has "+ eyecolor+" eyes and is "+age+" years old."
print childinfo(15, "John", "blue")
The output of that function call would be 15 had John eyes and is blue years old.  As you can see, getting the order of your parameters correct is imperative.

No comments:

Post a Comment