Functionnnn
Functionnnn
Functionnnn
def fun(*var):
function body
We can pass any number of arguments to this function. Internally all these values
are represented in the form of a tuple.
Example
def addition(*numbers):
total = 0
for no in numbers:
total = total + no
print("Sum is:", total)
# 0 arguments
addition()
# 5 arguments
addition(10, 5, 2, 5, 4)
# 3 arguments
addition(78, 7, 2.5)
Output
Sum is: 0
Sum is: 26
# function
def calculator(a, b):
add = a + b
# return the addition
return add
# call function
# take return value in variable
res = calculator(20, 5)
# function
def even_odd(n):
# check numne ris even or odd
if n % 2 == 0:
print('Even number')
else:
print('Odd Number')
Python Functions
In Python, the function is a block of code defined with a name. We use functions whenever we
need to perform the same task multiple times without writing the same code again. It can take
arguments and returns the value.
Consider a scenario where we need to do some action/task many times. We can define that action
only once using a function and call that function whenever required to do the same activity.
Function improves efficiency and reduces errors because of the reusability of a code. Once we
create a function, we can call it anywhere and anytime. The benefit of using a function is
reusability and modularity.
Types of Functions
Python support two types of functions
1. Built-in function
2. User-defined function
Built-in function
The functions which are come along with Python itself are called a built-in
function or predefined function. Some of them are listed below.
range(), id(), type(), input(), eval() etc.
Example: Python range() function generates the immutable sequence of numbers starting from
the given start integer to the stop integer.
Run
User-defined function
Functions which are created by programmer explicitly according to the requirement are called a
user-defined function.
Creating a Function
Use the following steps to to define a function in Python.
Use the def keyword with the function name to define a function.
Next, pass the number of parameters as per your requirement. (Optional).
Next, define the function body with a block of code. This block of code is nothing but the action
you wanted to perform.
In Python, no need to specify curly braces for the function body. The only indentation is
essential to separate code blocks. Otherwise, you will get an error.
Syntax of creating a function
Here,
function_name: Function name is the name of the function. We can give any name to function.
parameter: Parameter is the value passed to the function. We can pass any number of
parameters. Function body uses the parameter’s value to perform an action
function_body: The function body is a block of code that performs some task. This block of code
is nothing but the action you wanted to accomplish.
return value: Return value is the output of the function.
Note: While defining a function, we use two keywords, def (mandatory) and return (optional).
# function
def message():
print("Welcome to PYnative")
Run
Output
Welcome to PYnative
In this example, we are creating function with two parameters ‘ name’ and ‘age’.
# function
def course_func(name, course_name):
print("Hello", name, "Welcome to PYnative")
print("Your course name is", course_name)
# call function
course_func('John', 'Python')
Run
Output
# function
def calculator(a, b):
add = a + b
# return the addition
return add
# call function
# take return value in variable
res = calculator(20, 5)
Run
Calling a function
Once we defined a function or finalized structure, we can call that function by using its name.
We can also call that function from another function or program by importing it.
To call a function, use the name of the function with the parenthesis, and if the function accepts
parameters, then pass those parameters in the parenthesis.
Example
# function
def even_odd(n):
# check numne ris even or odd
if n % 2 == 0:
print('Even number')
else:
print('Odd Number')
Run
First, we need to use the import statement to import a specific function from a module.
Next, we can call that function by its name.
# import randint function
from random import randint
Run
Docstrings
In Python, the documentation string is also called a docstring. It is a descriptive text (like a
comment) written by a programmer to let others know what block of code does.
We write docstring in source code and define it immediately after module, class, function, or
method definition.
It is being declared using triple single quotes (''' ''') or triple-double quote(""" """).
We can access docstring using doc attribute (__doc__) for any object like list, tuple, dict, and
user-defined function, etc.
Single-Line Docstring
The single-line docstring is a docstring that fits in one line. We can use the triple single or triple-
double quotes to define it. The Opening and closing quotes need to be the same. By convention,
we should use to use the triple-double quotes to define docstring.
def factorial(x):
"""This function returns the factorial of a given number."""
return x
Run
Output
When you use the help function to get the information of any function, it returns the docstring.
Run
Output
factorial(x)
None
Multi-Line Docstring
A multi-line Docstrings is the same single-line Docstrings, but it is followed by a single blank
line with the descriptive text.
Example
def any_fun(parameter1):
"""
Description of function
Arguments:
parameter1(int):Description of parameter1
Returns:
int value
"""
print(any_fun.__doc__)
Run
Output
Description of function
Arguments
parameter1(int):Description of parameter1
Returns:
int value
In Python, to return value from the function, a return statement is used. It returns
the value of the expression following the returns keyword.
def fun():
statement-1
statement-2
statement-3
.
.
return [expression]
def is_even(list1):
even_num = []
for n in list1:
if n % 2 == 0:
even_num.append(n)
# return a list
return even_num
print("Addition: ", a)
print("Subtraction: ", b)
print("Multiplication: ", c)
print("Division: ", d)
Example
addition(10, 2)
Python Functions
In Python, the function is a block of code defined with a name. We use functions whenever we
need to perform the same task multiple times without writing the same code again. It can take
arguments and returns the value.
Python has a DRY principle like other programming languages. DRY stands for Don’t Repeat
Yourself. Consider a scenario where we need to do some action/task many times. We can define
that action only once using a function and call that function whenever required to do the same
activity.
Function improves efficiency and reduces errors because of the reusability of a code. Once we
create a function, we can call it anywhere and anytime. The benefit of using a function is
reusability and modularity.
The function helps us to organize code. The function accepts parameters as input, processes
them, and in the end, returns values as output.
Let’s assume we defined a function that computes some task. When we call that function from
another function, the program controller goes to that function, does some computation, and
returns some value as output to the caller function.
We cannot access the local variables from outside of the function. Because the scope is local,
those variables are not visible from the outside of the function.
Note: The inner function does have access to the outer function’s local scope.
When we are executing a function, the life of the variables is up to running time. Once we return
from the function, those variables get destroyed. So function does no need to remember the value
of a variable from its previous call.
Example
global_lang = 'DataScience'
def var_scope_test():
local_lang = 'Python'
print(local_lang)
var_scope_test()
# Output 'Python'
# outside of function
print(global_lang)
# Output 'DataScience'
Run
In the above example, we print the local and global variable values from outside of the function.
The global variable is accessible with its name global_lang.
But when we try to access the local variable with its name local_lang, we got a NameError,
because the local variable is not accessible from outside of the function.
If we try to access the local variable from the outside of the function, we will get the error as
NameError.
Example
def function1():
# local variable
loc_var = 888
print("Value is :", loc_var)
def function2():
A Global variable is a variable that declares outside of the function. The scope of
a global variable is broad. It is accessible in all functions of the same module.
Example
global_var = 999
def function1():
print("Value in 1nd function :", global_var)
def function2():
print("Value in 2nd function :", global_var)
function1()
function2()
Run
Output
In Python, global is the keyword used to access the actual global variable from
outside the function. we use the global keyword for two purposes:
Let’s see what happens when we don’t use global keyword to access the global
variable in the function
# Global variable
global_var = 5
def function1():
print("Value in 1st function :", global_var)
def function2():
# Modify global variable
# function will treat it as a local variable
global_var = 555
print("Value in 2nd function :", global_var)
def function3():
print("Value in 3rd function :", global_var)
function1(
function2()
function3()
Run
Output
As you can see, function2() treated global_var as a new variable (local variable). To
solve such issues or access/modify global variables inside a function, we use
the global keyword.
Example:
# Global variable
x = 5
function1()
function2()
function3()
Run
Output
In Python, nonlocal is the keyword used to declare a variable that acts as a global
variable for a nested function (i.e., function within another function).
We can use a nonlocal keyword when we want to declare a variable in the local
scope but act as a global scope.
Example
def outer_func():
x = 777
def inner_func():
# local variable now acts as global variable
nonlocal x
x = 700
print("value of x inside inner function is :", x)
inner_func()
print("value of x inside outer function is :", x)
outer_func()
Run
Output
1. Positional arguments
2. keyword arguments
3. Default arguments
4. Variable-length arguments
Positional Arguments
Example
add(50, 10)
# Output 40
add(10, 50)
# Output -40
Run
If you try to use pass more parameters you will get an error.
add(105, 561, 4)
Run
Output
Keyword Arguments
Example
message(name="John", surname="Wilson")
message(surname="Ault", name="Kelly")
Run
Output
Example
# correct use
message("John", "Wilson")
message("John", last_nm="Wilson")
# Error
# SyntaxError: positional argument follows keyword argument
message(first_nm="John", "Wilson")
Run
Default Arguments
Default arguments take the default value during the function call if we do not
pass them. We can assign a default value to an argument in function definition
using the = assignment operator.
For example, A function show_employee() that accepts the employee’s name and
salary and displays both. Let’s modify a function definition and assigned a default
value 8000 to a salary. Next, if salary value is missing in the function call, the
function automatically takes default value 9000 as a salary.
Example
Run
Output
Hello John
Hello Guest
Variable-length Arguments
def fun(*var):
function body
We can pass any number of arguments to this function. Internally all these values
are represented in the form of a tuple.
Example
def addition(*numbers):
total = 0
for no in numbers:
total = total + no
print("Sum is:", total)
# 0 arguments
addition()
# 5 arguments
addition(10, 5, 2, 5, 4)
# 3 arguments
addition(78, 7, 2.5)
Run
Output
Sum is: 0
Sum is: 26
Sum is: 87.5
Recursive Function
A recursive function is a function that calls itself, again and again.
factorial(5)
5*factorial(4)
5*4*factorial(3)
5*4*3*factorial(2)
5*4*3*2*factorial(1)
5*4*3*2*1 = 120
Example
def factorial(no):
if no == 0:
return 1
else:
return no * factorial(no - 1)
Run
Output
1. The recursive function takes more memory and time for execution.
2. Debugging is not easy for the recursive function.