Functions do three things:
1. They name pieces of code the way variables name strings and numbers.
2. They take arguments the way your scripts take argv.
3. Using #1 and #2 they let you make your own "mini scripts" or "tiny commands".
You can create a function by using the word def in Python. I'm going to have you make four different functions that work like your scripts, and then show you how each one is related.
#!/usr/bin/env python# -*- coding: utf-8 -*-# this one is like your scripts with argvdef print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2)# ok, that *args is actually pointless, we can just do thisdef print_two_again(arg1, arg2): print "arg1: %r, arg2: %r" % (arg1, arg2)# this just takes one argumentdef print_one(arg1): print "arg1: %r" % arg1def print_none(): print "I got nothin'."print_two ("Zed" ,"Shaw")print_two_again ("Zed","Shaw")print_one ("First!" )print_none()
result:
Let's break down the first function, print_two which is the most similar to what you already know from making scripts:
1. First we tell Python we want to make a function using def for "define".
2. On the same line as def we then give the function a name, in this case we just called it "print_two" but it could be "peanuts" too. It doesn't matter, except that your function should have a short name that says what it does.
3. Then we tell it we want *args (asterisk args) which is a lot like your argv parameter but for functions. This has to go inside () parenthesis to work.
4. Then we end this line with a : colon, and start indenting.
5. After the colon all the lines that are indented 4 spaces will become attached to this name, print_two. Our first indented line is one that unpacks the arguments the same as with your scripts.
6. To demonstrate how it works we print these arguments out, just like we would in a script.
Now, the problem with print_two is that it's not the easiest way to make a function. In Python we can skip the whole unpacking args and just use the names we want right inside (). That's what print_two_again does.
After that you have an example of how you make a function that takes one argument in print_one.
Finally you have a function that has no arguments in print_none.