You are on page 1of 26

Python Function

Python Function
● Functions are the most important aspect of an application.
● A function can be defined as the organized block of reusable code, which can
be called whenever required.
● Python allows us to divide a large program into the basic building blocks
known as a function.
Advantage of Functions in Python

There are the following advantages of Python functions.


● Using functions, we can avoid rewriting the same logic/code again and again
in a program.
● We can call Python functions multiple times in a program and anywhere in a
program.
● We can track a large Python program easily when it is divided into multiple
functions.
● Reusability is the main achievement of Python functions.
● However, Function calling is always overhead in a Python program.
Types of Functions

Basically, we can divide functions into the following two types:


1. Built-in functions - Functions that are built into Python.
2. User-defined functions - Functions defined by the users themselves.
Syntax of Function

def function_name(parameters):
"""docstring"""
statement(s)
Syntax of Function

1. Keyword def that marks the start of the function header.


2. A function name to uniquely identify the function. Function naming follows the
same rules of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are
optional.
4. A colon (:) to mark the end of the function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements
must have the same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.
Function Calling

● Once we have defined a function, we can call it from another function,


program, or even the Python prompt.
● To call a function we simply type the function name with appropriate
parameters.
● In python, the function definition should always be present before the function
call. Otherwise, we will get an error.
Function Calling

#function definition

def hello_world():

print("hello world")

# function calling

hello_world()

Output:

hello world
The return statement

The return statement is used at the end of the function and returns the result of the
function.

It terminates the function execution and transfers the result where the function is
called.

The return statement cannot be used outside of the function.


The return statement

Syntax

return [expression_list]

It can contain the expression which gets evaluated and value is returned to the caller
function.

If the return statement has no expression or does not exist itself in the function then it
returns the None object.
The return statement

# Defining function
def sum():
a = 10
b = 20
c = a+b
return c
# calling sum() function in print statement
print("The sum is:",sum())
Output:
The sum is: 30
Arguments in function

● The arguments are types of information which can be passed into the
function.
● The arguments are specified in the parentheses.
● We can pass any number of arguments, but they must be separate them with
a comma.
Example
#Python function to calculate the sum of two variables
#defining the function
def sum (a,b): Enter a: 10
return a+b; Enter b: 20
Sum = 30
#taking values from the user
a = int(input("Enter a: "))
b = int(input("Enter b: "))
#printing the sum of a and b
print("Sum = ",sum(a,b))
Types of arguments

1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
Required Arguments

● The required arguments are the arguments which are required to be passed at the
time of function calling with the exact match of their positions in the function
call and function definition.

● If either of the arguments is not provided in the function call, or the position of
the arguments is changed, the Python interpreter will show the error.
Required Arguments

#the function simple_interest accepts three


arguments and returns the simple interest
accordingly
def simple_interest(p,t,r): Enter the principle amount: 5000
Enter the rate of interest: 5
return (p*t*r)/100 Enter the time in years: 3
Simple Interest: 750.0
p = float(input("Enter the principle amount?
"))
r = float(input("Enter the rate of interest? "))
t = float(input("Enter the time in years? "))
print("Simple Interest: ",simple_interest(p,t,r))
Required Arguments

#the function calculate returns the sum of two arguments a and b

def calculate(a,b):

return a+b

>>> calculate(10) # this causes an error as we are missing a required arguments b.

Output:

TypeError: calculate() missing 1 required positional argument: 'b'


Default Arguments

● Python allows us to initialize the arguments at the function definition.

● If the value of any of this arguments is not provided at the time of function
call, then that argument can be initialized with the value given in the
definition even if the argument is not specified at the function call.
Default Arguments

def printme(name,age=22):
print("My name is",name,"and age is",age)
>>>printme("Arya")
#the variable age is not passed into the function however the default value of age
is considered in the function

>>> printme(“Arya”, 24)

#the value of age is overwritten here, 24 will be printed as age


Variable-length Arguments (*args)

● In large projects, sometimes we may not know the number of arguments to be


passed in advance.
● In such cases, Python provides us the flexibility to offer the comma-separated
values which are internally treated as tuples at the function call.
● By using the variable-length arguments, we can pass any number of arguments.
● However, at the function definition, we define the variable-length argument using
the *<variable - name >.
Variable-length Arguments (*args)

def printme(*names):

print("type of passed argument is ",type(names))

print("printing the passed arguments...")

for name in names:

print(name)

>>>printme("john","David","smith","nick")
Variable-length Arguments (*args)

In the above code, we passed *names as variable-length argument.

We called the function and passed values which are treated as tuple internally.

The tuple is an iterable sequence the same as the list.

To print the given values, we iterated *arg names using for loop.
Keyword arguments

● Python allows us to call the function with the keyword arguments.


● This kind of function call will enable us to pass the arguments in the random order.
● The name of the arguments is treated as the keywords and matched in the function
calling and definition.
● If the same match is found, the values of the arguments are copied in the function
definition.
Keyword arguments

#The function simple_interest(p, t, r) is called with the keyword arguments the


#order of arguments doesn't matter in this case

def simple_interest(p,t,r):

return (p*t*r)/100

print("Simple Interest: ", simple_interest(t=10,r=10,p=1900))


Recursive Functions
A function that calls itself is known as recursive function and the process
of calling function itself is known as recursion.

It is the process of calling a function by itself, until some specified


condition is satisfied.

It is used for repetitive computation (eg: factorial of a number) in which each


action is stated in term of previous result.
Recursive Functions
A function which calls itself is a recursive function
Example
def factorial(n):
if n==0 :
return 1
else :
return n * factorial(n-1)

>>> factorial(5)
120

You might also like