Functions
Functions
Functions
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:
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
Example:
def greet():
print('Hello World!')
Function in Python
def greet():
print('Hello World!')
Python Function
def greet():
print('Hello World!')
print('Outside function’)
How the program works:
Function in Python
Output:
Square Root of 4 is 2.0
2 to the power 3 is 8
Function in Python
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
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)
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)
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')
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
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))