Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put some
commonly or repeatedly done tasks together and make a function so that instead of writing the
same code again and again for different inputs, we can do the function calls to reuse code contained
in it over and over again.
Types of Functions
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 Declaration
The syntax to declare a function is:
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
Calling a Function
def greet():
print('Hello World!')
# call the function
greet()
When the function is called, the control of the program goes to the function definition.
All codes inside the function are executed.
The control of the program jumps to the next statement after the function call.
Function Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
# function with two arguments
def add_numbers(num1, num2):
sum = num1 + num2
print("Sum: ",sum)
# function call with two values
add_numbers(5, 4)
Parameters or Arguments
The terms parameter and argument can be used for the same thing: information that are passed into
a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called
User-defined functions
No argument and no return value
No argument and a return value
With argument(s) and no return value
With argument(s) and a return value
No argument and no return value
def Adding():
a = 20
b = 30
Sum = a + b
print("After Calling :", Sum)
Adding()
No argument and a return value
def Multiplication():
a = 10
b = 25
Multi = a * b
return Multi
print("After Calling the Multiplication : ", Multiplication())
With argument(s) and no return value
def Multiplications(a, b):
Multi = a * b
print("After Calling the Function:", Multi)
Multiplications(10, 20)
With argument(s) and a return value
def Addition(a, b):
Sum = a + b
return Sum
# We are calling it Outside the Definition
print("After Calling :", Addition(25, 45))
What is function overloading in Python?
As the name suggests, function overloading is the process where the same function can be used
multiple times by passing a different number of parameters as arguments. But Python does not
support function overloading.
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.
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks')
Output:
Positional Arguments
We used 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
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
# You will get correct output because
# argument is given in order
print("Case-1:")
nameAge("Suraj", 27)
# You will get incorrect output because
# argument is not in order
print("\nCase-2:")
nameAge(27, "Suraj")
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)
Example 1: Variable length non-keywords argument
# Python program to illustrate
# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print(arg)
myFun('Hello', 'Welcome', 'to', 'ks')
Example 2: Variable length keyword arguments
# Python program to illustrate
# *kwargs for variable number of keyword arguments
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))
# Driver code
myFun(first='ks', mid='for', last='ks')
Docstring
The first string after the function is called the Document string or Docstring in short. This is used to
describe the functionality of the function. The use of docstring in functions is optional but it is
considered a good practice.
The below syntax can be used to print out the docstring of a function.
Syntax: print(function_name.__doc__)
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.
# Python code to illustrate the cube of a number
# using lambda function
def cube(x): return x*x*x
cube_v2 = lambda x : x*x*x
print(cube(7))
print(cube_v2(7))