Functions

You have already used functions. For example, this code uses the functions raw_input, abs, int (which are all built-in), and the sqrt function (part of the math package):
      import math
      root2 = 2
      expo = float(raw_input("Gimme an exponent"))
      x = int(root2 ** expo)
      print 'nearest value is', x
    
How do we create functions? Just use the def keyword. For example:
      def square(x):
          return x * x
    
will create a function called square, which does what it says.

Parts of a function

A function definition has several parts: Not all parts are present all the time. For example, the function random.random() has no arguments. Also you can omit the return statement if the function changes some global variables, but other produces no direct output.

Using functions

Once you've defined a function, you can simply "call" it, by using it in some expression in the code. For example:
      def square(x):
          return x * x

      a = 3
      b = 4
      hypotenuse = math.sqrt(square(a) + square(b))
    
Notice that the name of the argument x doesn't have to match the names of the values being passed in, a and b.

Functions must be defined before they are used. For example, the following will not work:

      a = 3
      b = 4
      hypotenuse = math.sqrt(square(a) + square(b))

      def square(x):
          return x * x
    

Examples

Here is a function that determines whether a number is prime or not:
      import math

      def isPrime(x):
          for d in range(2, int(math.sqrt(x)) + 1):
              if x % d == 0:
                  return False
          return True
    
If x, the function returns True. If not, it returns False. Notice line 6: return False. Suppose x is 10. The first time through the loop, d is 2, and x % d == 0 is True, so line 6 will be executed.

At that point, isPrime will stop further execution. A return statement ends the function immediately, just as a break statement ends a loop.

The Goldbach conjecture says that there are an infinite number of prime pairs. A prime pair is two prime numbers, which differ by 2. Consider these prime numbers:

Here, 3 and 5 are prime pairs (because 5-3=2), 71 and 73 are prime pairs (becaure 73-71=2), but 37 and 41 are not (because 41-37=2, not 4).

Let's define a function that says whether its argument is part of a prime pair:

        def isPrimePair(x):
            return isPrime(x) and isPrime(x + 2)
      
Easy, eh? Just use the isPrime function we wrote previously! As you can see, it's perfectly OK to call one function from inside another function.

Finally, let's find all prime pairs less than a million:

        def findPrimePairs():
            for n in range(1000000):
                if isPrimePair(n):
                    print 'prime pair:', n, n+2
      
Notice that the function findPrimePairs take no arguments (there's nothing between the parentheses). You can do that.

If we type all the above code into a file, and run it, nothing happens! Why not? Because the above code simply defines the functions. It doesn't run them. To actually make the whole thing go, we have to call findPrimePairs(), at the bottom:

        import math

        def isPrime(x):
            for d in range(2, int(math.sqrt(x)) + 1):
                if x % d == 0:
                    return False
            return True

        def isPrimePair(n):
            return isPrime(n) and isPrime(n + 2)

        def findPrimePairs():
            for x in range(1000000):
                if isPrimePair(x):
                    print 'prime pair: ', x, x+2

        findPrimePairs()
      
Now, let's run it. Here's the output:
        pair found:  0 2
        pair found:  1 3
        pair found:  3 5
        pair found:  5 7
        pair found:  11 13
        pair found:  17 19
        pair found:  29 31
        pair found:  41 43
        pair found:  59 61
        pair found:  71 73
        pair found:  101 103
        ...
      
Whoa! How do me stop this thing? Easy: Control-C (hold down "Ctrl", and press C. This will kill the python program that is currently running.