FUNCTIONS
A function is a group of related statements that performs a specific task.
Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes the code reusable.
Syntax:
def function_name(parameters):
"""docstring"""
statement(s)
Above shown is a function definition that consists of the following components.
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.
This is how a function works:
Example:
def display():
print("This is a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
display()
Advantages of functions
o By including functions, we can prevent repeating the same code block repeatedly in
a program.
o Dividing the program into smaller functions make the program easier to understand
o A function once defined, can be called many times and from anywhere in a program.
o It is easy to debug the program in case of any error.
Arguments
Python supports various types of arguments that can be passed at the time of the
function call. Information can be passed into functions as arguments.
Example 1:
def display(user):
print("Welcome " + user +" !")
display("Kabir")
Output:
Welcome Kabir !
Example 2:
def display(user):
print(user)
display(user="Kabir")
Output:
Kabir
Example 3:
def display(user1, user2):
print("Welcome " + user1 +" and "+user2)
display("Kabir","Vishal")
Output:
Welcome Kabir and Vishal
Example 4:
def display(user1, user2):
print("Welcome " + user1 +" and "+user2)
display("Kabir")
Output:
Error
Default Argument
In case user do not wish to send any argument in the function, by default the default
argument will work. 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 display(user="unknown"):
print("Hello "+user)
display("Kabir")
display()
Output:
Hello Kabir
Hello unknown
Keyword arguments
The idea is to allow the caller to specify the argument name with values so that caller
does not need to remember the order of parameters.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters.
Example:
def fun1(friend,brother):
print("Friend=",friend)
print("brother=",brother)
fun1(friend="Kavita",brother="Kapil")
fun1(brother="Kapil",friend="Kavita")
Output:
Friend= Kavita
brother= Kapil
Friend= Kavita
brother= Kapil
Argument Vs Parameter
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.
Variable-length arguments
In Python, we can pass a variable number of arguments to a function using special
symbols. There are two special symbols:
*args (Non-Keyword Arguments)
**kwargs (Keyword Arguments)
Arbitrary Arguments OR Non keyword, *args
There may be certain situation when we do not know the number of arguments that user
will pass at the time of calling the function. In such cases, we can add a * before the
parameter name in the function definition.
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword
variable arguments.
Example 1:
def display(*friends):
print(friends)
display("Kabir")
display("Kabir","Riva")
display("Kabir","Riva","Abhay")
Output:
('Kabir',)
('Kabir', 'Riva')
('Kabir', 'Riva', 'Abhay')
Arbitrary Keyword Arguments, **kwargs
If you do not know how many keyword arguments that will be passed into your function,
add two asterisk: ** before the parameter name in the function definition.
Example:
def display(**friends):
print(friends)
display(friend1="Kabir")
display(friend1="Kabir",friend2="Riva")
display(friend1="Kabir",friend2="Riva",friend3="Abhay")
Output:
{'friend1': 'Kabir'}
{'friend1': 'Kabir', 'friend2': 'Riva'}
{'friend1': 'Kabir', 'friend2': 'Riva', 'friend3': 'Abhay'}
Returning a value
A function is able to return a value after the desired task is complete using return keyword.
The return statement is used to exit a function and go back to the place from where it was
called.
This statement can contain an expression that gets evaluated and the value is returned. If
there is no expression in the statement or the return statement itself is not present inside a
function, then the function will return the none object.
Example:
def square(x):
return x * x
print(square(5)) OR ans=square(5) print(ans)
Output:
25
The pass Statement
function definitions cannot be empty, but if you for some reason have a function definition
with no content, put in the pass statement to avoid getting an error.
def myfunction():
pass
Docstring
The first string after the function header is called the docstring and is short for
documentation string. It is briefly used to explain what a function does.
Although optional, documentation is a good programming practice. Unless you can
remember what you had for dinner last week, always document your code.
In the above example, we have a docstring immediately below the function header. We
generally use triple quotes so that docstring can extend up to multiple lines.
The use of docstring in functions is optional but it is considered a good practice.
Example:
def evenOdd(x):
"""Function to check if the number is even or odd"""
Recursion
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function
calls itself. This has the benefit of meaning that you can loop through data to reach a result.
The developer should be very careful with recursion as it can be quite easy to slip into
writing a function which never terminates, or one that uses excess amounts of memory or
processor power. However, when written correctly recursion can be a very efficient and
mathematically-elegant approach to programming.
In this example, tri_recursion() is a function that we have defined to call itself ("recurse").
We use the k variable as the data, which decrements (-1) every time we recurse. The
recursion ends when the condition is not greater than 0 (i.e. when it is 0).
To a new developer it can take some time to work out how exactly this works, best way to
find out is by testing and modifying it.
Example:
def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)
result=factorial(5)
print(result)
Output:
120
Anonymous functions
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.
These functions are called anonymous because they are not declared in the standard
manner by using the def keyword. You can use the lambda keyword to create small
anonymous functions.
Lambda forms can take any number of arguments but return just one value in the
form of an expression.
An anonymous function cannot be a direct call to print because lambda requires an
expression
Lambda functions have their own local namespace and cannot access variables
other than those in their parameter list and those in the global namespace.
Lambda's are a one-line version of a function.
Syntax:
lambda [arg1 [,arg2,.....argn]]:expression
Example 1:
sq=lambda x : x*x
print(sq(2))
Output:
Example 2:
sum=lambda x,y : x+y
print("Sum= ",sum(5,10))
Output:
Sum= 15
Scope and Lifetime of a variable
Scope
The area of a program where a variable is acknowledged is its scope. A function's defined
parameters and variables are not accessible from outside the function. They therefore have
a localised scope.
All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python −
Global variables
Local variables
Global vs. Local variables
Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.
This means that local variables can be accessed only inside the function in which they are
declared, whereas global variables can be accessed throughout the program body by all
functions.
Lifetime
A variable's lifetime is the time frame during which it is stored in memory. The lifetime of
variables inside a function is as long as the function executes.
Once we go back from the function, they are destroyed. As a result, a function forgets the
value of a variable from earlier calls.
Example 1:
def fun1():
a=5
print("Value inside function:",a)
fun1()
Output:
Value inside function: 5
Example 2:
def fun1():
a=5
print("Value inside function:",a)
fun1()
print(a)
Output:
Error
Example 3:
def fun1():
a=5
print("Local to function:",a)
fun1()
a=10
print(a)
Output:
Value inside function: 5
10
The variable a inside the function is different (local to the function) from the one outside.
Although they have the same names, they are two different variables with different scopes.
On the other hand, variables outside of the function are visible from inside. They have a
global scope.
Types of Functions
Basically, we can divide functions into the following two types:
1. Built-in functions - Functions that are built into Python.
Python has several functions that are readily available for use. These functions are called
built-in functions.
Some of the built-in functions are:
abs()
This function returns the absolute value of the given number.
Example:
a=-12
print(abs(a))
Output:
12
all()
This function returns True if all elements in the given iterable are true. If not, it returns
False.
Example:
l = [1, 3, 0, 5]
print(all(l))
Output:
False
any()
This function returns True if any element of an iterable is True. If not, it returns False.
Example:
l = [1, 3, 0, 5]
print(any(l))
Output:
True
The any() function returns True if any element of an iterable is True. If not, it
returns False.
Example:
ascii()
This method replaces a non-printable character with its corresponding ascii value and
returns it.
text = 'Pythön is interesting'
# replace ö with its ascii value
print(ascii(text))
Output:
'Pyth\xf6n * interesting'
bin()
This method converts a specified integer number to its binary representation and
returns it.
Example:
n = 20
# convert 15 to its binary equivalent
print('The binary equivalent of number is', bin(n))
Output:
The binary equivalent of number is 0b10100
2. User-defined functions - Functions defined by the users themselves.
Functions that we define ourselves to do certain specific task are referred as user-defined
functions.
Functions that readily come with Python are called built-in functions. If we use functions
written by others in the form of library, it can be termed as library functions.
Pass by Reference vs. Value
In the Python programming language, all arguments are supplied by reference. It implies
that if we modify the value of an argument within a function, the change is also reflected in
the calling function.
Example 1:
def fun1(a ):
a=a+10
print("Value in function= ",a)
return a
# calling the defined function
a=10
result = fun1(a)
print( "Number returned from function: ",result)
Output:
Value in function= 20
Number returned from function: 20
Example 2:
def fun1(list1):
list1.append(5)
print("List in function= ",list1)
return list1
# calling the defined function
list1=[1,2,3,4]
result = fun1(list1)
print( "Number returned from function: ",result)
Output:
List in function= [1, 2, 3, 4, 5]
Number returned from function: [1, 2, 3, 4, 5]