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().
We use def keyword to define a function. general syntax is like
def functionname(params):
statement1
statement2Let 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):
z = s
z = [x for x in z]
z.reverse()
if s == "".join(z):
return True
else:
return False
s = raw_input("Enter a string: ")
if palindrome(s):
print "Yay a palindrome"
else:
print "Oh no, not a palindrome"Now run the code :)