A "function machine" |
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