Вы находитесь на странице: 1из 12

Python Functions

A Function is a block of statements for a particular task.

A Function can be called as a section of a program that is written once and can be
executed whenever required in the program, thus making code reusability.

A Function is a subprogram that works on data and produce some output.

Types of Functions:

There are two types of Functions.

a) Built-in Functions: Functions that are predefined. We have used many


predefined functions in Python.

b) User- Defined: Functions that are created according to the requirements.

Defining a Function:

Keyword def is used to start the Function Definition. Def specifies the starting of
Function block.

Syntax:

def functionname (arguments):

“”” DOC STRING”””

body of function

Invoking a Function:

To execute a function block it needs to be called. This is called function calling.

Syntax:

function_name(parameters)

eg:
#Providing Function Definition

def sum(x,y):

s=x+y

print "Sum of two numbers is"

print s

#Calling the sum Function

sum(10,20)

sum(20,30)

NOTE: Function call will be executed in the order in which it is called.

return Statement:

return[expression] is used to send back the control to the caller with the
expression.

In case no expression is given after return it will return None.

In other words return statement is used to exit the Function definition.

Eg:

def sum(a,b):

"Adding the two values"

print "Printing within Function"

print a+b

return a+b

def msg():
print "Hello"

return

total=sum(10,20)

print ?Printing Outside: ?,total

msg()

print "Rest of code"

Passing Parameters

Apart from matching the parameters, there are other ways of matching the
parameters.

Python supports following types of formal argument:

1) Positional argument (Required argument).

2) Default argument.

3) Keyword argument (Named argument)

Positional/Required Arguments:

When the function call statement must match the number and order of
arguments as defined in the function definition it is Positional Argument
matching.
Eg:

#Function definition of sum

def sum(a,b):

"Function having two parameters"

c=a+b

print c

sum(10,20)

sum(20)

Default Arguments

Default Argument is the argument which provides the default values to the
parameters passed in the function definition, in case value is not provided in the
function call.

Eg:

#Function Definition

def msg(Id,Name,Age=21):

"Printing the passed value"

Print( Id )
print (Name )

print (Age )

return

#Function call

msg(Id=100,Name='Ravi',Age=20)

msg(Id=101,Name='Ratan')

Keyword Arguments:

Using the Keyword Argument, the argument passed in function call is matched
with function definition on the basis of the name of the parameter.

Eg:

def msg(id,name):

"Printing passed value"

print (id)

print (name)

return

msg(id=100,name='Raj')

msg(name='Rahul',id=101)

Anonymous Function:

Anonymous Functions are the functions that are not bond to name.

Anonymous Functions are created by using a keyword "lambda".

Lambda takes any number of arguments and returns an evaluated expression.


Lambda is created without using the def keyword.

Syntax:

lambda args:expression

#Function Definiton

square=lambda x1: x1*x1

#Calling square as a function

print "Square of number is",square(10)

Difference between Normal Functions and Anonymous Function:

Eg:

Normal function:

#Function Definiton

def square(x):

return x*x

#Calling square function

print "Square of number is",square(10)

Anonymous function:

#Function Definiton

square=lambda x1: x1*x1


#Calling square as a function

print "Square of number is",square(10)

Use of Lambda Function

We use lambda functions when we require a nameless function for a short period
of time.

In Python, we generally use it as an argument to a higher-order function (a


function that takes in other functions as arguments). Lambda functions are used
along with built-in functions like filter(), map() etc.

Example use with filter()

The filter() function in Python takes in a function and a list as arguments.

The function is called with all the items in the list and a new list is returned which
contains items for which the function evaluats to True.

# Program to filter out

# only the even items from

# a list using filter() and

# lambda functions

my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(filter(lambda x: (x%2 == 0) , my_list))

# Output: [4, 6, 8, 12]

print(new_list)

Example use with map()

The map() function in Python takes in a function and a list.


The function is called with all the items in the list and a new list is returned which
contains items returned by that function for each item.

# Program to double each

# item in a list using map() and

# lambda functions

my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(map(lambda x: x * 2 , my_list))

# Output: [2, 10, 8, 12, 16, 22, 6, 24]

print(new_list)

# Python Program to display the powers of 2 using anonymous function

# Uncomment to take number of terms from user

terms = int(input("Enter the no of terms? "))

# use anonymous function

result = list(map(lambda x: 2 ** x, range(terms)))

# display the result

print("The total terms is:",terms)

for i in range(terms):

print("2 raised to power",i,"is",result[i])

# Python Program to find numbers divisible by thirteen from a list using


anonymous function

# Take a list of numbers


my_list = [12, 65, 54, 39, 102, 339, 221,]

# use anonymous function to filter

result = list(filter(lambda x: (x % 13 == 0), my_list))

# display the result

print("Numbers divisible by 13 are",result)

1) Local Variables:

Variables declared inside a function body is known as Local Variable. These have a
local access thus these variables cannot be accessed outside the function body in
which they are declared.

Eg:

def msg():

a=10

print "Value of a is",a

return

msg()

print a
#it will show error since variable is local

b) Global Variable:

Variable defined outside the function is called Global Variable. Global variable is
accessed all over program thus global variable have widest accessibility.

Eg:

b=20

def msg():

a=10

print "Value of a is",a

print "Value of b is",b

return

msg()

print b

RECURSION

Recursion is the process of defining something in terms of itself.

A function calling itself repeatedly.

# find the factorial of a number

def calc_factorial(x):

"""This is a recursive function

to find the factorial of an integer"""


if x == 1:

return 1

else:

return (x * calc_factorial(x-1))

num = 4

print("The factorial of", num, "is", calc_factorial(num))

Generating Fibonacci series by using recursive functions

def recur_fibo(n):

"""Recursive function to

print Fibonacci sequence"""

if n <= 1:

return n

else:

return(recur_fibo(n-1) + recur_fibo(n-2))

nterms = int(input("How many terms? "))

# check if the number of terms is valid

if nterms <= 0:

print("Plese enter a positive integer")

else:

print("Fibonacci sequence:")

for i in range(nterms):
print(recur_fibo(i))

Вам также может понравиться