Python Language / Python Functions

It is set of lines of code used to perform a particular task. We can send parameters / data to a function and it may or may not have return values. It is created using def keyword in python.

Sample Programs
Program Output
#Function Creation
def our_function():
 print("Function Defined")
#Calling a Function
def our_function():
print("Function Defined and Called")
our_function()
Function Defined and Called
#Passing Parameters to functions
def our_function(fname):
 print(" Welcome to " + fname + " Concept")
our_function("Parameters ")
Welcome to Parameters Concept
#Default Parameter Value
def our_function(fruitname = "Orange"):
 print("Fruit Name: " + fruitname)
our_function("Apple")
our_function("Mango")
our_function()
our_function("Grape")
Fruit Name: Apple
Fruit Name: Mango
Fruit Name: Orange
Fruit Name: Grape
#Passing a List as a Parameter
def our_function(FruitName):
 for x in FruitName:
  print(x)
fruits = ["Mango", "Orange", "Papaya"]
our_function(fruits)
Mango
Orange
Papaya
#Return Values
def add_function(x,y):
 return x + y
print(add_function(2,3))
5

Example: Recursion program for calculating fib series

Recursion
The function can calling itself is called as recursion. Its purpose is loop through data to reach a result.

Program Output
def Fibseries(n):
if n<0:
print("Incorrect input")
elif n==1:
return 0
elif n==2:
return 1
else:
return Fibseries(n-1)+Fibseries(n-2)
print(Fibseries(9))
21

Lambda Function
It takes number of arguments, but can only have one expression. Use lambda functions when an anonymous function is required for a short period of time.

Example

write a program to use lambda function to adds 10 to the number passed as a argument and print result:

Program Output
s = lambda x : x +6
print(s(5))
11
Numberssum = lambda x, y  : x + y
print(Numberssum (2,3))
5
def Our_function(y):
 return lambda x : x + y
sumofnumber = Our_function(4)
print(sumofnumber(5))
9


Home     Back