Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 15

Function in Python

Python Functions
A function is a block of code that performs a specific task.

Suppose, you need to create a program to create a circle and color it. You can
create two functions to solve this problem:

 create a circle function


 create a color function
Dividing a complex problem into smaller chunks makes our program easy to
understand and reuse.

Types of function
There are two types of function in Python programming:

Standard library functions - These are built-in functions in Python that are
available to use.
User-defined functions - We can create our own functions based on our
requirements.
Function in Python

Python Function Declaration


The syntax to declare a function is:
def function_name(arguments):
# function body
return
Here,
 def - keyword used to declare a function
 function_name - any name given to the function
 arguments - any value passed to function
 return (optional) - returns value from a function

Example:
def greet():
print('Hello World!')
Function in Python

Calling a Function in Python:


we have declared a function named greet().

def greet():
print('Hello World!')

Here's how we can call the greet() function in Python.

# call the function


greet()
Function in Python

Python Function
def greet():
print('Hello World!')

# call the function


greet()

print('Outside function’)
How the program works:
Function in Python

Advantages of Python Functions


We can stop a program from repeatedly using the same code block by
including functions.

 1. Code Reusable - We can use the same function multiple times in


our program which makes our code reusable.
 2. Code Readability - Functions help us break our code into chunks
to make our program readable and easy to understand.
Note: Functions calling has always been overhead in a Python
program.
Function in Python

Python Library Functions


In Python, standard library functions are the built-in functions that can
be used directly in our program. For example,

 print() - prints the string inside the quotation marks


 sqrt() - returns the square root of a number
 pow() - returns the power of a number
These library functions are defined inside the module. And, to use
them we must include the module inside our program.

For example, sqrt() is defined inside the math module.


Function in Python

Python Library Function


import math
square_root = math.sqrt(4)
print("Square Root of 4 is",square_root)
power = pow(2, 3)
print("2 to the power 3 is",power)

Output:
Square Root of 4 is 2.0
2 to the power 3 is 8
Function in Python

Python Function Arguments


Arguments are the values passed inside the parenthesis of the function. A function can have
any number of arguments separated by a comma.

From a function's perspective:


 A parameter is the variable listed inside the parentheses in the function definition(formal
arguments).

 An argument is the value that is sent to the function when it is called (actual arguments).

#A simple function to check whether the number passed as an argument to the #function is
even or odd.

def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
evenOdd(2)
evenOdd(3)
Function in Python

Types of Function Arguments


Python supports various types of arguments that can be passed at the
time of the function call. In Python, we have the following 4 types of
function arguments.
 Default argument

 Keyword arguments (named arguments)

 Positional arguments (Required arguments)

 Arbitrary arguments (variable-length arguments *args and


**kwargs)
Function in Python

Default Arguments
A default argument is a parameter that assumes a default value if a value is not
provided in the function call for that argument.

Example:
def add_numbers( a = 7, b = 8):
sum = a + b
print('Sum:', sum)

# function call with two arguments


add_numbers(2, 3)

# function call with one argument


add_numbers(a = 2)

# function call with no arguments


Function in Python

Keyword Arguments
The idea is to allow the caller to specify the argument name with
values so that the caller does not need to remember the order of
parameters.
Example:
# Python program to demonstrate Keyword Arguments
def employee(firstname, lastname):
print(firstname, lastname)

# Keyword arguments
employee(firstname='Rajneesh', lastname='Singh')
employee(lastname='Singh', firstname='Rajneesh')
Function in Python

Positional Arguments
The Position argument during the function call so that the first argument (or value) is
assigned to name and the second argument (or value) is assigned to age. By changing
the position, or if you forget the order of the positions, the values can be used in the
wrong places, as shown in the Case-2 example below, where 41 is assigned to the name
and Rajneesh is assigned to the age.

Example:
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)

# argument is given in order


print("Case-1:")
nameAge("Rajneesh", 41)

# argument is not in order


print("\nCase-2:")
nameAge(41, "Rajneesh")
Function in Python

Arbitrary Keyword Arguments


In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable number of
arguments to a function using special symbols. There are two special symbols:

 *args in Python (Non-Keyword Arguments)


 **kwargs in Python (Keyword Arguments)

# program to find sum of multiple numbers

def find_sum(*numbers):
result = 0
def myFun(*argv):
for num in numbers:
for arg in argv:
result = result + num print(arg)
print("Sum = ", result) myFun('Hello', 'Welcome', 'to', 'Python')

# function call with 3 arguments


find_sum(1, 2, 3)

# function call with 2 arguments


find_sum(4, 9)
Function in Python

Example 2: Variable length keyword arguments

def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))
# Driver code
myFun(first='Rajneesh', mid='Kumar', last='Singh')
Function in Python

Anonymous Functions in Python


In Python, an anonymous function means that a function is without a name. As we
already know the def keyword is used to define the normal functions and the
lambda keyword is used to create anonymous functions.

Lambda functions have exactly one line in their syntax:


lambda [argument1 [,argument2... .argumentn]] : expression

Example:
lambda_ = lambda argument1, argument2: argument1 + argument2;
print( "Value of the function is : ", lambda_( 20, 30 ) )
print( "Value of the function is : ", lambda_( 40, 50 ) )

Examples:
def cube(x): return x*x*x
cube_v2 = lambda x : x*x*x
print(cube(7))

You might also like