PDA

View Full Version : TUTORIAL: functions


inkedmn
05-24-2002, 10:43 PM
This is an brief introduction to the use of functions in python. Hope you enjoy it :)

functions are defined by a 'def' statement, like this:

def functionname():


they are assigned a name that will be used to call them. basically, a function is a piece of code that can be used repeatedly, but needs only to be typed once :).

so, let's do our first function. we'll call this function "printer" because it's going to do just that: print :). here it is:

def printer(x):
print x

pretty simple, eh? the 'x' in the parenthesis after the name of the function is called an argument. in this case, whatever you pass to the printer function will be printed. here are some examples using the python interactive interpreter:

>>> def printer(x):
... print x
...
>>> printer('hello')
hello
>>> printer('this is an argument')
this is an argument


ok, now let's try one with multiple arguments. we'll do one that gives the product of two numbers...


def multiplier(x, y):
total = x * y
print total

and here's how it would look in the interpreter:

>>> def multiplier(x, y):
... total = x * y
... print total
...
>>> multiplier(3, 6)
18
>>> multiplier(34, 13)
442


now for something a bit crazier...
we're going to learn how to use the "return" statement. "return" allows you to return a value once the function has finished running. that way, you can assign the value of a function to a variable, and it will be equal to whatever is returned. here's an example:


def something(x):
total = x * 25
return total


now, here's how it'd look when it's run


>>> def something(x):
... total = x * 25
... return total
...
>>> blah = something(4)
>>> print blah
100
>>> blah2 = something(18)
>>> print blah2
450


there's just one more point i feel i should make regarding functions. you've seen alot of variables defined within the functions we've created (like "total" in the last example). these are called "local" variables because they're only accessible within the function. if you try to call "total" outside of the function, it will tell you that function is not defined, like this:


>>> def something(x):
... total = 10
... product = total * x
... print product
...
>>> something(5)
50
>>> print total
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'total' is not defined



make sense?

there are also "global" variables, which can be accessed from outside the function. these variables must be declared as global, like this:


def something(x):
global total
total = 10
product = total * x
print product



now, look what happens when we try to access "total" from outside the function:


>>> def something(x):
... global total
... total = 10
... product = total * x
... print product
...
>>> something(4)
40
>>> print total
10


i must warn you though, global variables are (in my experience)
not very popular with the larger python community and should be used only when absolutely necessary...

well, that's about it.

email me at inkedmn@inkedmn.net if you have any comments/questions, or just post them here...

PACE!

xilica
05-24-2002, 10:53 PM
Excellently written...... i guess now that i have BROKEN the ICE at this site people are gonna take after me.... its kew its kew....... well i like this tutorial.... its good ...

by the way, where do i code my python? which text editor?

inkedmn
05-24-2002, 11:06 PM
any editor you want.

i'm guessing you'll be using notepad.

xilica
05-24-2002, 11:15 PM
is python coded for the web? or where do i run or compile it after i write it in notepad..... i am interested in learning python since i have looked at your "madz catz" skillz in the competition section and it seems that python is not a language to "poo poo".

inkedmn
05-24-2002, 11:17 PM
www.python.org/doc

go read it, it'll answer any question you have

KumaSan
05-25-2002, 03:15 AM
Thanks for the help ink. I was learning python by myself until work sent me to perl class a couple weeks ago. I need all the help I can get these days...

inkedmn
05-25-2002, 06:44 PM
Originally posted by KumaSan
Thanks for the help ink. I was learning python by myself until work sent me to perl class a couple weeks ago. I need all the help I can get these days...


if there's ever a specific topic/area in python that you (or anyone else, i guess) is having trouble with, go ahead and ask someone to go over it here, tutorial style (and i'll help if i know how to do what you want :))

anyway, welcome aboard :)

Strike
05-25-2002, 09:00 PM
One of the cool things that I learned about Python functions when writing moobot is the ability of Python to utilize functions with arbitrary length argument lists. In fact, it can do this in two forms - using a list (array) of arguments, or using a dict (hash) of arguments for named element access.

Example using a list:

def myFunction(*args):
for arg in args:
print arg

This will print every argument passed to it, like so:

>>> myFunction("foo", 3, [0, 1, 2], {'a': 1, 'b': 2})
foo
3
[0, 1, 2]
{'a': 1, 'b': 2}

So, you use the *varName syntax to specify a list of arguments. Then you can use any arbitrary number of arguments.

You can also, like I said, do the same thing, but with a dict:

def myOtherFunction(**args):
for key in args.keys():
print "%s: %s" % (key, args[key])

This code does the same thing as the one above, only for a dict as an argument. Like so:

>>> myOtherFunction(a=1, b=2)
a: 1
b: 2


Enjoy :)

Benny
09-02-2002, 12:13 AM
Just thought I'd add a little something I only just realised..

when defining a function - you can do something like this:


>>> def a(x, y=1):
... print x
... print y
...
>>> a(2)
2
1
>>> a(2, 3)
2
3


By me having y=1 when I define the function, it means y will always have the value 1, unless specified a different value when the function is called.

I only just found this out and thought it was pretty nifty.

inkedmn
09-02-2002, 12:16 AM
yeah, default values are pretty nice :)

Halide
10-10-2002, 09:08 PM
support for arbitrary parameters! :)

~praise python

BlackMamba
01-15-2004, 05:33 PM
i have no idea how the hell that works

Strike
01-15-2004, 08:57 PM
Originally posted by BlackMamba
i have no idea how the hell that works
Thanks for your insightful post.