Product SiteDocumentation Site

Chapter 9. Functions

9.1. Defining a function
9.2. Local and global variables
9.3. Default argument value
9.4. Keyword arguments
9.5. Docstrings

Reusing the same code is required many times within a same program. Functions help us to do so. We write the things we have to do repeatedly in a function then call it where ever required. We already saw build in functions like len(), divmod().

9.1. Defining a function

We use def keyword to define a function. general syntax is like
def functionname(params):
    statement1
    statement2

Let us write a function which will take two integers as input and then return the sum.
>>> def sum(a, b):
...     return a + b

In the second line with the return keyword, we are sending back the value of a + b to the caller. You must call it like
>>> res = sum(234234, 34453546464)
>>> res
34453780698L

Remember the palindrome program we wrote in the last chapter. Let us write a function which will check if a given string is palindrome or not, then return True or False.
#!/usr/bin/env python
def palindrome(s):
    return s == s[::-1]

if __name__ = '__main__':
	s = raw_input("Enter a string: ")
	if palindrome(s):
	    print "Yay a palindrome"
	else:
    	print "Oh no, not a palindrome"

Now run the code :)