A Byte of Python

Chapter 7. Functions

Table of Contents

Introduction
Defining a Function
Function Parameters
Using Function Parameters
Local Variables
Using Local Variables
Using the global statement
Default Argument Values
Using Default Argument Values
Keyword Arguments
Using Keyword Arguments
The return statement
Using the literal statement
DocStrings
Using DocStrings
Summary

Introduction

Functions are reusable pieces of programs. They allow you to give a name to a block of statements and you can run that block using that name anywhere in your program and any number of times. This is known as calling the function. We have already used many built-in functions such as the len and range.

Functions are defined using the def keyword. This is followed by an identifier name for the function followed by a pair of parentheses which may enclose some names of variables and the line ends with a colon. Next follows the block of statements that are part of this function. An example will show that this is actually very simple:

Defining a Function

Example 7.1. Defining a function

				
#!/usr/bin/python
# Filename: function1.py

def sayHello():
	print 'Hello World!' # block belonging to the function
# End of function

sayHello() # call the function
				
				

Output

				
$ python function1.py
Hello World!
				
				

How It Works

We define a function called sayHello using the syntax as explained above. This function takes no parameters and hence there are no variables declared in the parentheses. Parameters to functions are just input to the function so that we can pass in different values to it and get back corresponding results.