Functions
Functions
Functions help break our program into smaller and modular chunks. As our program grows
Syntax:
def function_name(parameters):
"""docstring"""
statement(s)
2. A function name to uniquely identify the function. Function naming follows the same rules
3. Parameters (arguments) through which we pass values to a function. They are optional.
Example:
def display():
print("This is a function")
Calling a Function
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.
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):
display("Kabir")
Output:
Welcome Kabir !
Example 2:
def display(user):
print(user)
display(user="Kabir")
Output:
Kabir
Example 3:
display("Kabir","Vishal")
Output:
Example 4:
def display(user1, 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.
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)
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')
def display(**friends):
print(friends)
display(friend1="Kabir")
display(friend1="Kabir",friend2="Riva")
display(friend1="Kabir",friend2="Riva",friend3="Abhay")
Output:
{'friend1': 'Kabir'}
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
Output:
25
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
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.
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.
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
Syntax:
lambda [arg1 [,arg2,.....argn]]:expression
Example 1:
sq=lambda x : x*x
print(sq(2))
Output:
Example 2:
print("Sum= ",sum(5,10))
Output:
Sum= 15
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
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
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
fun1()
Output:
Example 2:
def fun1():
a=5
fun1()
print(a)
Output:
Error
Example 3:
def fun1():
a=5
print("Local to function:",a)
fun1()
a=10
print(a)
Output:
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
Python has several functions that are readily available for use. These functions are called
built-in functions.
abs()
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.
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
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
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
return a
a=10
result = fun1(a)
Output:
Value in function= 20
Example 2:
def fun1(list1):
list1.append(5)
return list1
list1=[1,2,3,4]
result = fun1(list1)
Output: