/* jquery */ /* jquery accordion style*/ /* jquery init */

Learn Python - Creating Functions

Now we understand the benefits it's now time to create a function. We'll start with a simple one that calculates the area of a circle.

Open the Geany editor using the Desktop menu option 'Programming->Geany' and create a new file using the 'File->New' menu option. Now save it as 'func.py' in the 'Python' folder we created on the Desktop in a previous post.

Type in the source code below. Take care to correctly enter those quotes, colons and line indentations. And save your typing frequently.

1
2
3
4
5
6
7
8
9
10
11
12
# A simple function definition and call example
# Created by David Briddock

import math

# find the area of a circle for a specified radius
def circleArea(radius):
  return math.pi * (radius*radius)

radius = input("Circle radius? ")
area = circleArea(radius)
print ("Area is ") + format(area)

After the program-level comments and the 'math' module import statement we reach the function definition at line 6. Notice the comments. Comments are even more important for functions and should clearly describe the function's behaviour.

Now let's consider the code in lines 7 and 8.

Line 7 starts with the 'def' keyword. This tells Python we are defining a function. Next is the function name, which must be unique to our program. When reading the code we want to be able to determine what the function from its name, so make sure the you choose is appropriate and meaningful one. Here I've used the so-called camel case naming standard to to help with readability.

All functions will have a pair of brackets, or parenthesis, after the name. Optionally there may be one or more parameters declared inside these brackets. Here there is just one called 'radius', which will contain a numeric radius value. Finally, there's a colon ':' at the end of the definition. A colon signifies that all the indented code below will belong to this function, and will be executed when it is called.

In this case our function only has a single line of code. Line 8 calculates the area of a circle, using the 'math' module's constant 'math.pi'. Once calculated this value is then returned back to the statement that called the function.

Now for the main code. On line 10 the user is asked to input a 'radius' value.

Line 11 calls the 'circleArea' function with the user-supplied 'radius' value as the parameter. The returned value is assigned to a variable called 'area'.

And finally line 12 prints out a message and the value of 'area'.

Creating your own functions is a major step in becoming a more accomplished programmer. Study any well written program and you'll see functions everywhere.

A post from my Learn Python on the Raspberry Pi tutorial.