On Apr 17, 2005, at 17:29, Joseph Quigley wrote:

So what do you use the
def bar(x, y):
        return x + y

bar(4, 5)

functions for? (I just need a simple example)

Whenever you have something that you may want to do more than once and/or in more than one place in your program. Here's a small example: a dice-rolling function. Say you're writing a program to automate some part of a roleplaying game. At some point you'll want to roll dice. So instead of writing the code to do that every time, you just call the rollDice function, supplying the number and type of dice you want to roll. If you need to roll 2D6, just call rollDice(2, 6).




#!/usr/bin/env python

import random

def rollDice(numDice, numSides):
    dice = [random.randint(1, numSides) for i in range(numDice)]
    return dice



        Here it is in action:

>>> rollDice(2, 6)
[1, 4]


Note that rollDice itself calls functions: the randint function from the random module, and the built-in range function. (it also uses a list comprehension, but that's another topic)


-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?"


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to