Functions in Python

Welcome to my Blog, In this article you learn brief description of functions in python

Definition of function

A function is a block of code ,reusable code that is used to perform a action and python gives many built in function like print() but you can create a own function.Python Function take zero or more arguments and return a value. We create a function using the def keyword.

There are a three types of functions in Python:
  1. built-in : built-in functions,such as help(),max(),min(),print() and more of these functions click here
  2. User Defined Functions:
  3. Anonymous functions,which are also called lambda function because they are not started with def keyword.

2) User Defined Functions some examples here:

def hello():
	print("Hello World")

if you not pass any return value then function return an object None when call a function if return value is exist then function return a result see example below:

def hello():
	return "Hello World"
hello() #Hello World
  1. Function with Arguments:

Arguments are which are given to any function when function call.while the function refers to the arguments by their parameter names. There are four types of arguments:

a) Default arguments.
b) Required arguments.
c) Keyword arguments.
d) Variable number of arguments.

a) Default Arguments:

Default arguments those are take a default value if you no argument passed during the function can define the default value with = operator.

def plus(a,b = 2):
  return a + b

b) Required arguments:

They are required arguments need to be passed when call an function.

def plus(a,b):
  return a + b

c) Keyword arguments:

You can use the keyword arguments in your function call. You use these to identify the arguments by their parameter name and example below:

def add(a,b):
  return a + b
# Call 'add()' function with keyword arguments
add(a=1, b=2)

d) Variable Number of Arguments:

When you do not know exact number of arguments that you want to pass to function in this case you can use *args keyword to get all parameters:

def add(*args):
  return sum(args)

3) Anonymous Functions in Python:

some examples of Anonymous functions in python:

double = lambda x: x*2

sum = lambda x, y: x + y;

from functools import reduce
my_list = [1,2,3,4,5,6,7,8,9,10]

# Use lambda function with 'filter()'
filtered_list = list(filter(lambda x: (x*2 > 10), my_list))

# Use lambda function with 'map()'
mapped_list = list(map(lambda x: x*2, my_list))

# Use lambda function with 'reduce()'
reduced_list = reduce(lambda x, y: x+y, my_list)


if you like the article share with your friends.if you have any question or query related to article and have an any suggestions please leave in comment box.

Thanks for reading the Article.

Leave a Reply

Your email address will not be published. Required fields are marked *