[go: up one dir, main page]

0% found this document useful (0 votes)
60 views11 pages

3 - Functions

Python functions allow for code reusability and modularity. Functions are defined using the def keyword followed by the function name and parameters in parentheses. Functions can take in arguments, return values, and use different argument types like positional, keyword, and default arguments. Lambda functions are anonymous one-line functions declared using the lambda keyword. Modules help organize code into reusable files that can be imported and used in other Python files. Built-in modules contain many useful functions for tasks like mathematics, file handling, and more.

Uploaded by

ravi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views11 pages

3 - Functions

Python functions allow for code reusability and modularity. Functions are defined using the def keyword followed by the function name and parameters in parentheses. Functions can take in arguments, return values, and use different argument types like positional, keyword, and default arguments. Lambda functions are anonymous one-line functions declared using the lambda keyword. Modules help organize code into reusable files that can be imported and used in other Python files. Built-in modules contain many useful functions for tasks like mathematics, file handling, and more.

Uploaded by

ravi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

FUNCTIONS

Python Functions

 A Function is a self block of code.


 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.

Defining a Function:

A Function defined in Python should follow the following format:

1) Keyword def is used to start the Function Definition. Def specifies the starting of
Function block.
2) def is followed by function-name followed by parenthesis.
3) Parameters are passed inside the parenthesis. At the end a colon is marked.

Example:
def add():
a=10
b=20
c=a+b
print(c)

add()
print('hello')
add()

output:
30
hello
30
# Function with arguments
def add(a,b):
c=a+b
print(c)

add(5,8)
print('hello ')
add(4,6)

output:
13
hello
10

#Function with return value


def add(a,b):
c=a+b
return c

x=add(5,8)
y=add(4,6)
print(x+y)

Output:
23

Types of Arguments

1) Positional argument
2) Keyword argument

3) Default argument.

1. Positional Arguments
def add(a,b):
print(a+b)

add(10,20)
print('one')
add(20,30)

output:
30
one
30

2. Keyword Arguments
def add(a,b):
print(a)

add(b=10,a=20)
print('one')
add(20,30)

Output:
30
one
50
3. default arguments
def add(a,b=5):
print(a)

add(20)
add(10,20)
add(b=10,a=20)
output:
25
30
30

Anonymous Function or Lambda Functions


Python allows us to not declare the function in the standard manner, i.e., by using the def
keyword. Rather, the anonymous functions are declared by using lambda keyword.

Example 1 def x(a):


x=lambda a:a*a print(a*a)
print(x(5))
x(5)
Output:
25

Example 2
x=lambda a,b:a+b
print(x(10,20))
output:
30

Example 3
x=lambda a,b,c:a+b+c
print(x(10,20,30))
output:
60

Use of lambda function with filter


List = [1,2,3,4,10,123,22]
Oddlist = list(filter(lambda x:(x%3 == 0),List)) 
print(Oddlist)  
Output:
[3, 123]

Use of lambda function with map


List = {1,2,3,4,10,22,123}  
new_list = list(map(lambda x:x*3,List)) 
print(new_list)  
Output:
[3, 6, 9, 12, 30, 66, 369]

*args and **kwargs in Python

In Python, we can pass a variable number of arguments to a function


using special symbols. There are two special symbols:
 *args (Non Keyword Arguments)
 **kwargs (Keyword Arguments)
We use *args and **kwargs as an argument when we are unsure
about the number of arguments to pass in the functions.

Python *args
In the function, we should use an asterisk * before the parameter
name to pass variable length arguments.The arguments are passed as
a tuple and these passed arguments make tuple inside the function
with same name as the parameter excluding asterisk *.

Example 2: Using *args to pass the variable length arguments to the


function
def adder(*num):
sum = 0

for n in num:
sum = sum + n

print("Sum:",sum)

adder(3,5)
adder(4,5,6,7)
adder(1,2,3,5,6)

When we run the above program, the output will be


Sum: 8
Sum: 22
Sum: 17

In the above program, we used *num as a parameter which allows us


to pass variable length argument list to the adder() function. Inside
the function, we have a loop which adds the passed argument and
prints the result. We passed 3 different tuples with variable length as
an argument to the function.

Python **kwargs
Python passes variable length non keyword argument to function
using *args but we cannot use this to pass keyword argument. For this
problem Python has got a solution called **kwargs, it allows us to
pass the variable length of keyword arguments to the function.
In the function, we use the double asterisk ** before the parameter
name to denote this type of argument. The arguments are passed as a
dictionary and these arguments make a dictionary inside function
with name same as the parameter excluding double asterisk **.
Example 3: Using **kwargs to pass the variable keyword arguments
to the function 
def intro(**data):
print("\nData type of argument:",type(data))

for key, value in data.items():


print("{} is {}".format(key,value))

intro(Firstname="Sita", Lastname="Sharma", Age=22, Phone=1234567890)


intro(Firstname="John", Lastname="Wood", Email="johnwood@nomail.com", Country="Wakanda", Age=25, Phone=9876543210)

When we run the above program, the output will be


Data type of argument: <class 'dict'>
Firstname is Sita
Lastname is Sharma
Age is 22
Phone is 1234567890

Data type of argument: <class 'dict'>


Firstname is John
Lastname is Wood
Email is johnwood@nomail.com
Country is Wakanda
Age is 25
Phone is 9876543210

In the above program, we have a function intro() with **data as a


parameter. We passed two dictionaries with variable argument length
to the intro() function. We have for loop inside intro() function which
works on the data of passed dictionary and prints the value of the
dictionary…

Python Recursive Function

def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""

if x == 1:
return 1
else:
return (x * factorial(x-1))

num = 3
print("The factorial of", num, "is", factorial(num))

Output

The factorial of 3 is 6

Modules

1. Using import statement:


def add(a,b):  
    c=a+b  
    print (c)  
    return  

Save the file by the name addition.py. To import this file "import"
statement is used.

import addition  
addition.add(10,20)  
addition.add(30,40)  

Output:
 30  
70  
 

Example of importing multiple modules:

Eg:

1) msg.py:

def msg_method():  
    print ("Today the weather is rainy"  )
    return  
2) display.py:

def display_method():  
    print ("The weather is Sunny"  )
    return  

3) multiimport.py:

import msg,display  
msg.msg_method()  
display.display_method()  

Output:

Today the weather is rainy  
The weather is Sunny  
    

2) Using from.. import statement:

1) area.py

def circle(r):  
    print (3.14*r*r)  
    return  
  
def square(l):  
    print (l*l)  
    return  
  
def rectangle(l,b):  
print (l*b)  
return  
  
def triangle(b,h):  
print (0.5*b*h ) 
return  

2) area1.py

from area import square,rectangle  
square(10)  
rectangle(2,5)  
Output:

100  
10  

3) To import whole module:

1) area.py

def circle(r):  
    print 3.14*r*r  
    return  
  
def square(l):  
    print l*l  
    return  
  
def rectangle(l,b):  
print l*b  
return  
  
def triangle(b,h):  
print 0.5*b*h  

return  

2) area1.py

from area import *  
square(10)  
rectangle(2,5)  
circle(5)  
triangle(10,20)  

Output:

100  
10  
78.5  
100.0  

Built in Modules in Python:


import math  
a=4.6  
print (math.ceil(a) ) 
print math.floor(a)  
b=9  
print math.sqrt(b)  
print math.exp(3.0)  
print math.log(2.0)  
print math.pow(2.0,3.0)  
print math.sin(0)  
print math.cos(0)  
print math.tan(45)  

Output:

5.0  
4.0  
3.0  
20.0855369232  
0.69314718056  
8.0  
0.0  
1.0  
1.61977519054  

You might also like