Big title right? I am about to introduce you to the function! Dum dum dah! Every programmer will go on and on about functions and all the different ideas about how they work and what they do, but I will give you the simplest explanation you can use right now.
Functions do three things:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | # this one is like your scripts with argv
def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
# this just takes one argument
def print_one(arg1):
print "arg1: %r" % arg1
# this one takes no arguments
def print_none():
print "I got nothin'."
print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()
|
Let's break down the first function, print_two which is the most similar to what you already know from making scripts:
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.
Warning
This is very important. Do not get discouraged right now if this doesn't quite make sense. We're going to do a few exercises linking functions to your scripts and show you how to make more. For now just keep thinking "mini script" when I say "function" and keep playing with them.
If you run the above script you should see:
$ python ex18.py
arg1: 'Zed', arg2: 'Shaw'
arg1: 'Zed', arg2: 'Shaw'
arg1: 'First!'
I got nothin'.
$
Right away you can see how a function works. Notice that you used your functions the way you use things like exists, open, and other "commands". In fact, I've been tricking you because in Python those "commands" are just functions. This means you can make your own commands and use them in your scripts too.
Write out a function checklist for later exercises. Write these on an index card and keep it by you while you complete the rest of these exercises or until you feel you do not need it:
And when you run (aka "use" or "call") a function, check these things:
Use these two checklists on the remaining lessons until you do not need them anymore.
Finally, repeat this a few times:
"To 'run', 'call', or 'use' a function all mean the same thing."