Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

learning python part 4 (a look at functions)

  • Please log in to reply
2 replies to this topic

#1 saeras


    CC Resident

  • Just Joined
  • PipPipPipPip
  • 64 posts

Posted 15 February 2010 - 08:50 AM

Let's start of with a simple function

def add(a, b):
    return a+b

What this does is it defines the function add(). "a" and "b" are parameters that are requested upon calling it (not when you define it). It then does addition with "a" and "b" and returns them. So calling it could look like this:

c = add(5, 3)
#this would make
#output the number 8

Functions are fairly simple but powerful if used correctly.

A few notes about functions:
Functions uses their own namespace, meaning that they have their own set of variables unless specifically told otherwise. It's a good practice to let it use it's own variables and return the necessary values though.
Functions will be exited upon return command. Meaning that when return is called the function will be exited and the code coming after it will be ignored.
I have found this useful while doing recursions. Or if I have stacked up for loops and want it to end after a criteria is met (be careful not to overuse it though).

Now let's say you have a function that you want to have parameters with default but changeable values. This is easily done by this method:

def function(a, b, c=2, d=3, e=7):

In this function you have to enter a value for "a" and "b" but c,d and e will default at 2, 3 and 7. If you want to enter a value for say e. You do so in this manner.

function('value for a', 'value for b', e='value for e')

This way you don't have to enter a value for c and d too.

That pretty much concludes this tutorial. I was planning on having classes in here too but realized it was a little too much for me atm. However i will do classes in a later tutorial.
Stay tuned for part 5 where I'm gonna go through the usage of modules.

Feel anything have been left out? Had trouble with something? Or want something changed?
Post a comment about it and I will see what I can do.
  • 0
Posted Image

#2 totolzz


    CC Lurker

  • Just Joined
  • Pip
  • 4 posts

Posted 30 July 2010 - 11:23 PM

def function(a, b, c=2, d=3, e=7):

i didn't get this function.. what is the return for this?? print(hi)
  • 0

#3 totallynoob


    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 22 September 2011 - 02:13 PM

when print("hi") it will jus print hi (i think)
  • 0

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download