0% found this document useful (0 votes)
9 views

Function

Functions in Python are named blocks of code that perform specific tasks, allowing for code reuse and organization. They can take inputs (arguments), perform operations, and return outputs, reducing code duplication and increasing readability. There are built-in, module-defined, and user-defined functions, each with specific advantages and rules for naming and calling them.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Function

Functions in Python are named blocks of code that perform specific tasks, allowing for code reuse and organization. They can take inputs (arguments), perform operations, and return outputs, reducing code duplication and increasing readability. There are built-in, module-defined, and user-defined functions, each with specific advantages and rules for naming and calling them.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Functions

A function is a named blocks of code that perform a specific task. It contains line of code(s)
that are executed sequentially from top to bottom by Python interpreter.
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.

They help in organizing and reusing code by breaking it down into smaller, manageable
pieces. Functions can take inputs (known as arguments or parameters), perform operations,
and return outputs.
Note: Function avoids repetition and makes code reusable.

Some Benefits of Using Functions


• Functions reduce code duplication and make programs more easy to understand and
Maintain
• Increase Code Readability
• Increase Code Reusability
• Having identical (or similar) code in more than one place has various downsides:
➢ Don’t want to write the same code twice (or more)
➢ The code must be maintained in multiple places
➢ Code is harder to understand with big blocks of repeated code everywhere

Types of Functions
a) Built-in Functions: pre-defined functions and are always available for use. e.g. len(),
type(), int(), input() etc.
b) Defined in Module: pre-defined in particular modules and can only be used when the
corresponding module is imported. To use these modules in the program, a
programmer needs to write import statement as the first line of the program. Once you
import a module, you can reference (use), any of its functions or variables in your
code.
c) User- Defined Functions: Functions that we define ourselves to do certain specific
task are referred as user-defined functions. As programmers you can create your
own functions.

Advantages of user-defined functions


1. User-defined functions help to decompose a large program into small segments which
makes program easy to understand, maintain and debug.

Page 1 of 37
2. If repeated code occurs in a program. Function can be used to include those codes and
execute when needed by calling that function.
3. Programmers working on large project can divide the workload by making different
functions.

Rules for naming python function (identifier)


We follow the same rules when naming a function as we do when naming a variable.
1. It can begin with either of the following: A-Z, a-z, and underscore(_).
2. The rest of it can contain either of the following: A-Z, a-z, digits(0-9), and
underscore(_).
3. A reserved keyword may not be chosen as an identifier.

Syntax to declare python function:


def function_name(parameter1, parameter2, ...):
"""Docstring"""
# Function body (code block)
# Statements to Perform certain operations
# Return a value (optional)

Let's break down the different components of a function:


❖ def: It's the keyword used to define a function.
❖ function_name: This is the identifier for the function, which you can choose as per
your preference. It should follow the naming conventions of Python.
❖ parameters: These are optional variables that you can specify within the parentheses
after the function name. They act as placeholders for values that you pass to the
function when you call it.
❖ :: It denotes the end of the function declaration and the start of the function body or a
block.
❖ Function body: It consists of one or more statements that define the operations
performed by the function. This code block is indented under the function
declaration. (Definition of Indentation: The blank space in the beginning of a
statement (convention is four spaces) within a block.
❖ return statement: This statement is optional and is used to specify the value that the
function should return when it completes its execution.
Note: The non-indented statements that are below the function definition are not part of the
function definition.

Page 2 of 37
How to call a function in python?
To execute a function, it needs to be called. This is called 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.
Syntax
<function_name>(parameters)

Example
sum(a,b)

Here, sum is the function and a, b are the parameters passed to the function definition.

Example 1
def sum3(x,y,z):
"Going to add 3 variables x, y and z"
print ("sum3 of three numbers is", x+y+z)

def sum2(x,y):
return(x+y)

#Calling the sum Function This is not a part of


sum3(10,20,30) function sum3() and sum2().
ans=sum2(20,30)
(These statements are not
print ("sum2 of two numbers is", ans) indented and hence at top
print(sum3.__doc__) level of indentation.)
print(sum2.__doc__)
Output:
sum3 of three numbers is 60
sum2 of two numbers is 50
Going to add 3 variables x, y and z
None

Example 2
def sum3(x,y,z):
"Going to add 3 variables x, y and z"
print ("sum3 of three numbers is", x+y+z)

def sum2(x,y):

Page 3 of 37
return(x+y)

#Calling the sum Function


ans1=sum3(10,20,30) #Here sum3 function doesn’t return any value i.e. ans1=None
print ("sum3 of three numbers is", ans1)
ans2=sum2(20,30) #Here sum2 function return a value i.e. ans2=50
print ("sum2 of two numbers is", ans2)
Output:
sum3 of three numbers is 60
sum3 of three numbers is None
sum2 of two numbers is 50

Docstring
The first string after the function header is called the Document string or Docstring in short.
It is used to explain in brief, what a function does.
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__)
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. This string is
available to us as __doc__ attribute of the function.

Example:
>>> print(sum3.__doc__)
"Going to add 3 variables x, y and z"

The return statement


The return statement is used to exit a function and go back to the place from where it was
called.
Syntax of return

return [expression_list]

This statement can contain expression which 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.

Page 4 of 37
Example 1:
def sum(a,b):
"Adding the two values"
print("Printing within Function")
print(a+b)
return (a+b)

def msg():
print ("Hello")
return

total=sum(10,20)
print ("Printing Outside:",total)
msg()
print ("Rest of code")
Output:
Printing within Function
30
Printing Outside: 30
Hello
Rest of code

Example 2:
def sum(a,b):
"Adding the two values"
print("Printing within Function")
print(a+b)
return (a+b)

def msg():
print ("Hello")
return

total=sum(10,20)
print ("Printing Outside:",total)
print(msg())
print ("Rest of code")
Output:

Page 5 of 37
Printing within Function
30
Printing Outside: 30
Hello
None
Rest of code

Here, None is the returned value.

Example 3:
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))
Output:
2
4

Example 4:
def add_numbers(x,y):
sum = x + y
return sum
num1 = 5
num2 = 6
print("The sum is", add_numbers(num1, num2))
Output:
The sum is 11

Structure of a Python Program


In Python, generally all function definitions are given at the top followed by the statements
which are not part of any functions. These statements are not indented at all. These are often
called from the top-level statements. The python interpreter starts the execution of a program

Page 6 of 37
from the top-level statements. The top-level statements are part of the main program.
Internally Python gives a special name to the top-level statements as __main__.

def function1():
.
.
def function2():
.
.
def function3():
.
.

Python names the segment with


# top-level statements here top-level statement as __main__.
Statement1
Python begins execution of a
Statement1
program from __main__.
.
.

Python stores this name in a built-in variable called __name__. (you need not declare this
variable; you can directly use it.)

Example:
def printinfo():
print("My name is Ankur Sharma")

print("At the top-most level right now")


print("Inside:" ,__name__)
printinfo()
Output:
At the top-most level right now
Inside: __main__
My name is Ankur Sharma

Page 7 of 37
Function Argument and Parameter
There can be two types of data passed in the function.
• The First type of data is the data passed in the function call. This data is called
arguments.
• The second type of data is the data received in the function definition. This data is
called parameters.

Argument Parameter
Arguments are the values passed in when the Parameters are the name within the function
function is called. definition.
Arguments can be literals, variables and Parameters must be variable to hold
expressions. incoming values.
Arguments are probably going to be different Parameters don’t change when the program is
every time the function is called. running.
Arguments are also known as actual This is also known as formal parameters
parameters.

Example
def addition(x1,y1): # Here variable x1 and y1 are the parameters
print (x1+y1)
x=15
addition(x ,10) # Here variable x and value 10 are the arguments
addition(x,x) # Here variable x is the argument
y=20
addition(x,y) # Here variable x and y are the arguments
Output:
25
30
35

Passing Parameters
Apart from matching the parameters, there are other ways of matching the parameters.
Python supports following types of formal argument:
1. Positional argument (Required argument).
2. Default argument.
3. Keyword argument (Named argument)

Page 8 of 37
4. Arbitrary Arguments /Variable number of arguments

1. Positional/Required Arguments:
Required arguments are the arguments passed to a function in correct positional order. Here,
the number of arguments in the function call should match exactly with the function
definition. It is Positional Argument matching.

Positional Argument Example


#Function definition of sum
def sum(a,b):
"Function having two parameters"
c=a+b
print (c)
sum(10,20)
sum(20)
Output:
30
Traceback (most recent call last):
File "D:/pythonprograms/function1.py", line 8, in <module>
sum(20)
TypeError: sum() missing 1 required positional argument: 'b'

Explanation:
1) In the first case, when sum() function is called passing two values i.e., 10 and 20 it
matches with function definition parameter and hence 10 and 20 is assigned to a and b
respectively. The sum is calculated and printed.
2) In the second case, when sum() function is called passing a single value i.e., 20 , it is
passed to function definition. Function definition accepts two parameters whereas only one
value is being passed; hence it will show an error.

2. Default Arguments
You can assign default values to function parameters. A default value is a value that a
parameter takes if no argument is provided for it when the function is called. This allows you
to make certain parameters optional, providing a default value that will be used if no other
value is specified.
We can provide a default value to a parameter by using the assignment operator (=).

Default Argument Example1

Page 9 of 37
def msg(Id, Name, Age=21): # "Default value of Age=21"
print (Id)
print (Name)
print (Age)
msg(Id=100,Name='Ravi',Age=20)
msg(Id=101,Name='Ratan')
Output:
100
Ravi
20
101
Ratan
21

Explanation:
1) In first case, when msg() function is called passing three different values i.e., 100 , Ravi
and 20, these values will be assigned to respective parameters and thus respective values will
be printed.
2) In second case, when msg() function is called passing two values i.e., 101 and Ratan, these
values will be assigned to Id and Name respectively. No value is assigned for third argument
via function call and hence it will retain its default value i.e, 21.

Default Argument Example2


def msg(Id, Name='Ankur', Age): # "Default value of Name='Ankur'"
print (Id)
print (Name)
print (Age)
msg(Id=100,Name='Ravi',Age=20)
msg(Id=101,Age=21)
Output:
Error: non-default argument follows default argument

Explanation:
All default argument must come after the non-default argument.

3. 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.

Page 10 of 37
keyword Argument Example 1
def msg(id, name):
"Printing passed value"
print (id)
print (name)
msg(id=100, name='Raj')
msg(name='Rahul', id=101)
msg(35, name="Ankur Sharma")
Output:
100
Raj
101
Rahul
35
Ankur Sharma

Python allows functions to be called using keyword arguments. When we call functions in
this way, the order (position) of the arguments can be changed.
Explanation:
1) In the first case, when msg() function is called passing two values i.e., id and name the
position of parameter passed is same as that of function definition and hence values are
initialized to respective parameters in function definition. This is done on the basis of the
name of the parameter.
2) In second case, when msg() function is called passing two values i.e., name and id,
although the position of two parameters is different it initialize the value of id in Function
call to id in Function Definition and same with name parameter. Hence, values are
initialized on the basis of name of the parameter.

As we can see, we can mix positional arguments with keyword arguments during a
function call. But we must keep in mind that keyword arguments must follow positional
arguments.

keyword Argument Example 2


def msg(id,name):
"Printing passed value"
print (id)

Page 11 of 37
print (name)
msg(name="Ankur Sharma",35)

Explanation: Will result into error as:


Having a positional argument after keyword arguments will result into errors.
Or
SyntaxError: non-keyword arg after keyword arg

4. Arbitrary Arguments /Variable number of arguments


Sometimes, we do not know in advance the number of arguments that will be passed into a
function. Python allows us to handle this kind of situation through function calls with
arbitrary number of arguments.
In the function definition we use an asterisk (*) before the parameter name to denote this
kind of argument.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword
variable arguments. This tuple remains empty if no additional arguments are specified during
the function call.

Example 1:
def greet(*names):
"""This function greets all
the person in the names tuple."""

# names is a tuple with arguments


for name in names:
print("Hello",name)

greet("Monica","Luke","Steve","John")

Page 12 of 37
Output:
Hello Monica
Hello Luke
Hello Steve
Hello John

Here, we have called the function with multiple arguments. These arguments get wrapped up
into a tuple before being passed into the function. Inside the function, we use a for loop to
retrieve all the arguments back.

Example 2:
def plus(*args):
total = 0
for i in args:
total += i
return total

# Calculate the sum


print(plus(20,30,40,50))
Output:
140

Example 3:
def printinfo(arg1, *vartuple):
print("Output is: ")
print (arg1)
for var in vartuple:
print (var)
return;

printinfo(10)
printinfo(70, 60, 50)
Output:
Output is:
10
Output is:
70
60

Page 13 of 37
50

Returning values from the Function


Functions in Python may or may not return a value. There can be broadly two types of
functions in Python.
1. Functions returning some value (non-void functions): The functions that returns
some computed result in terms of a value, fall in this category. The computed value is
returned using returns statement as per the Syntax:
return <value>
The value being returned can be one of the following:
• a literal
• a variable
• an expression
When you call a function that is returning a value, the returned
value is made available to the caller function/program by
internally substituting the function called statement.
def sum(x,y):
s=x+y
return s
And we are invoking this function as:
result=sum(5,3)
After the function call to sum() function is successfully
completed, the returned value will internally substitute the
function call statement. That is, now the above statement will
become internally
result=8

Important Point 1:
The returned value of a function should be used in the caller
function/program inside an expression or a statement in the right
manner like the given below:
• result=sum(5,3)
• print(sum(3,4))
• sum(5,3)>7
If you do not use their value in any of these ways and just give
a stand-alone function call, Python will not report an error but
their return value is completely wasted.

Page 14 of 37
Important Point 2:
The return statement ends a function execution even if it is in
the middle of the function. A function ends the moment it reaches
a return statement or All statement in function-body have been
executed, whichever occurs earlier, following function will never
reach print() statement as return is reached before that.

Example:
import math
def printinfo(b):
ans=math.sqrt(b)
This statement is unreachable because
return ans
printinfo() function will end with return
print(ans) and control will never reach this
statement.
a=10
print(printinfo(a))

2. Functions not returning any value (void function): The functions that perform
some action but do not return any computed value to the caller function are called
void function. A void function may or may not have a return statement. If a void
function has a return statement, then it takes the following form:
return
that is, keyword return without any value or expression.

The void functions do not return a value but they return a legal empty value of python
i.e., None. Every void function returns a value None to its caller. So if need arises you
can assign this return value somewhere as per your needs.
Example 1:
def hello():
print("Hello")

Page 15 of 37
a=hello()
print(a)
Output:
Hello
None

Code 1: Code 2:
def hello(): def hello():
return "****"
print("Hello")
a=hello()
a=hello() print(a)
print(a)
Output: Output:
Hello ****
None

So, now you know that in Python you can have following four possible combinations of user
defined functions:
1) Function with no parameters and no return value
2) Function with no parameters but return value
3) Function with parameters but no return value
4) Function with parameters and return value
5) Functions with Multiple Return Values

Function with no parameters and no return value


A python function without any arguments/parameters means you cannot pass data.
A function which does not return any value cannot be used in an expression it can be used
only as independent statement.

Example:
def hello():
print("Hello")

hello()
Output:
Hello

Function with no parameters but return value


def hello():

Page 16 of 37
return "Hello Dear"

xyz=hello()
print(xyz)
Output:
Hello Dear

Function with parameters but no return value


Example:
def hello(name):
print("Hello, My name is", name)

hello("Amit")
Output:
Hello, My name is Amit

Function with parameters and return value


To have a function return a value after it is called, we need to use the return keyword.
Handling Return Values
❖ When Python encounters return, it
➢ Exits the function
➢ Returns control back to where the function was called
➢ Similar to reaching the end of a function
❖ The value provided in the return statement is sent back to the caller as an expression result
❖ The return value must be used at the calling place by –
➢ Either store it any variable
➢ Use with print()
➢ Use in any expression

NOTE: the return statement ends a function execution even if it is in the


middle of function. Anything written below return statement will become
unreachable code.

Example:
def sum(x,y):
s=x+y

Page 17 of 37
return s
result=sum(5,3)
print("sum=",result)
Output:
sum= 8

Functions with Multiple Return Values


Sometimes a function needs to return more than one value. Unlike other programming
languages, Python lets you returned more than one value from a function. To do this, simply
list more than one expression in the return statement.
To return multiple values from a function, you must ensure following things:
1) The return statement inside a function body should be of the form given below:
return <value1/variable1/expression1>, <value2/variable2/expression2>..
2) The function call statement should receive or use the returned values in one of the
following ways:
a. Either receive the returned values in form a tuple variable as shown below:
Example:
def squared(x,y,z):
return x*x,y*y,z*z # Return tuple, we could also write return (x*x,y*y,z*z)

t=squared(2,3,4)
print(type(t))
print(t)
Output:
<class 'tuple'>
(4, 9, 16)
b. Or you can directly unpack the received values of tuple by specifying the same
number of variables on the left-hand side of the assignment in function call
Example:
def squared(x,y,z):
return x*x,y*y,z*z
t1,t2,t3=squared(2,3,4)
print(t1,t2,t3)
Output:
4, 9, 16

Page 18 of 37
c. Either receive the returned values in form a list variable as shown below:
Example:
def squared(x,y,z):
return [x*x,y*y,z*z]
t=squared(2,3,4)
print(type(t))
print(t)
Output:
<class 'list'>
[4, 9, 16]
d. Either receive the returned values in form a dictionary variable as shown
below:
Example:
def squared(x,y,z):
d = dict();
d['x'] = x*x
d['y'] = y*y
d['z'] = z*z
return d
t=squared(2,3,4)
print(type(t))
print(t)
Output:
<class 'dict'>
{'x': 4, 'y': 9, 'z': 16}
e. Using ‘yield’
One alternative approach for returning multiple values from a function in
Python is to use the yield keyword in a generator function. A generator
function is a special type of function that returns an iterator object, which
generates a sequence of values on the fly, one value at a time.
To return multiple values from a generator function, you can use the yield
keyword to yield each value in turn. The generator function will then pause
execution until the next value is requested, at which point it will resume
execution and yield the next value. This process continues until the generator
function completes execution or encounters a return statement.

Page 19 of 37
Example: Example:
def squared(x,y,z): def get_values():
yield x*x yield 42
yield y*y yield 'hello'
yield z*z yield [1, 2, 3]

result = squared(2,3,4) result = get_values()


print(next(result)) print(next(result))
print(next(result)) print(next(result))
print(next(result)) print(next(result))
Output: Output:
4 42
9 hello
16 [1, 2, 3]

What is namespace?
In Python everything is an object. Thus, a name can hold any kind of value. A namespace is a
system that has a unique name for each and every object in Python. An object might be a
variable or a method. Python itself maintains a namespace in the form of a Python
dictionary. So, a namespace is a practical approach to define the scope and it helps to avoid
name conflicts. A namespace in Python is a collection of names. So, a namespace is
essentially a mapping of names to corresponding objects. It ensures that names are unique
and will not lead to any conflict.

Real-time example, the role of a namespace is like a surname. One might not find a single “Alice” in
the class there might be multiple “Alice” but when you particularly ask for “Alice Lee” or “Alice
Clark” (with a surname), there will be only one (time being don’t think of both first name and
surname are same for multiple students).
On similar lines, the Python interpreter understands what exact method or variable one is trying to
point to in the code, depending upon the namespace. So, the division of the word itself gives a little
more information. Its Name (which means name, a unique identifier) + Space(which talks something
related to scope). Here, a name might be of any Python method or variable and space depends upon
the location from where is trying to access a variable or a method.
Python uses namespaces to manage the scope and lifetime of variables and other identifiers.
Namespaces help prevent naming conflicts and enable you to organize your code effectively.

Page 20 of 37
Scope of Variables
The part of a program where a variable is accessible is called its scope. There are four major
types of variable scope or name resolution rule (also known as LEGB rule). LEGB stands
for Local → Enclosing → Global → Built-in.

Local Scope
Whenever you define a variable within a function, its scope lies ONLY within the
function. It is accessible from the point at which it is defined until the end of the
function and exists for as long as the function is executing. Which means its value
cannot be changed or even accessed from outside the function. Let's take a simple
example:
def print_number():
first_num = 1 # Local scope
print("The first number defined is: ", first_num)

print_number()
print("The first number defined is: ", first_num) # Raises an error
because first_num is not defined in this scope
Output:
The first number defined is: 1
Traceback (most recent call last):
File "D:\pythonprograms\function1.py", line 6, in <module>
print("The first number defined is: ", first_num)
NameError: name 'first_num' is not defined
Explanation:
• This code defines a function called print_number() that sets a
variable first_num to the value of 1 and then prints a message
that includes the value of first_num.
• When the function is called with print_number(), it will print
the message "The first number defined is: 1".
• However, when the function call is finished and the program
tries to print first_num again outside of the function, it
will result in a NameError because first_num is only defined
within the scope of the print_number() function.
• Therefore, the second print statement will not work.

Page 21 of 37
Enclosing Scope
What if we have a nested function i.e., function defined within another functions. And
when a variable is not found in the local scope of a function, Python searches in the
enclosing scopes, moving outward until it finds the variable or reaches the global
scope. This is known as the enclosing or non-local scope.
Let us see with the help of an example.
def outer():
first_num = 1 # Enclosing scope
def inner():
second_num = 2 # Local scope
print("first_num from outer: ", first_num) # Accesses first_num from the
enclosing scope
print("second_num from inner: ", second_num) # Accesses from the Local scope
inner()
print("second_num from inner: ", second_num) # Raises an error because second_num
is not defined in this scope

outer()
Output:
first_num from outer: 1
second_num from inner: 2
Traceback (most recent call last):
File "D:\pythonprograms\7th.py", line 11, in <module>
outer()
File "D:\pythonprograms\7th.py", line 9, in outer
print("second_num from inner: ", second_num)
NameError: name 'second_num' is not defined

Explanation:
• This code defines a function called outer(), which contains
another function called inner().
• When outer() is called, it first initializes a variable first_num
with the value of 1.
• Then it defines the inner() function, which initializes a variable
second_num with the value of 2.

Page 22 of 37
• The inner() function then prints the value of first_num (which is
in the scope of outer()) and second_num (which is in the scope of
inner()).
• After that, outer() calls inner(), which prints the values of
first_num and second_num.
• Finally, outer() tries to print the value of second_num again, but
this time it is outside the scope of inner() and therefore raises a
NameError because second_num is not defined in the scope of outer().

Got an error? This is because you cannot


access second_num from outer() (# Print statement 3). It is not
defined within that function. However, you can
access first_num from inner() (# Print statement 1), because the
scope of first_num is larger, it is within outer().
This is an enclosing scope. Outer's variables have a larger scope
and can be accessed from the enclosed function inner().

Scenario 1: Enclosing Scope


Here, we have a look at the outer() and inner() nested functions from the Enclosing
Scope example. Let's try to change the value of first_num from 1 to 0 from
within inner().
def outer():
first_num = 1
def inner():
first_num = 0
second_num = 1
print("inner - second_num is: ", second_num)
inner()
print("outer - first_num is: ", first_num)

outer()

Output:
inner - second_num is: 1
outer - first_num is: 1

Page 23 of 37
Explanation:
• This code defines a function called outer().
• Within outer(), there is another function called inner().
• When outer() is called, it first initializes a variable called
first_num to 1.
• It then calls inner().
• Within inner(), a new variable called first_num is initialized to
0.
• This variable is local to the inner() function and does not affect
the value of first_num in the outer() function.
• Another variable called second_num is initialized to 1.
• The function then prints the value of second_num.
• After inner() is called, outer() prints the value of first_num,
which is still 1 because the first_num variable within inner() is
local to that function and does not affect the value of first_num in
the outer() function.
• Therefore, the output of this code will be:``inner - second_num
is: 1outer - first_num is: 1``

It isn't always that simple, is it! For such purposes, we make use
of nonlocal keyword within Python.

Nonlocal Keyword
This is another handy keyword that allows us to work more flexibly and tidily with
variable scopes. The nonlocal keyword is useful in nested functions. It causes the
variable to refer to the previously bound variable in the closest enclosing scope. In
other words, it will prevent the variable from trying to bind locally first, and force it to
go a level 'higher up'. The syntax is similar to the global keyword.

def outer():
first_num = 1
def inner():
nonlocal first_num
first_num = 0
second_num = 1

Page 24 of 37
print("inner - second_num is: ", second_num)
inner()
print("outer - first_num is: ", first_num)

outer()
Output:
inner - second_num is: 1
outer - first_num is: 0
Explanation:
• This code defines a function called outer().
• Within outer(), there is another function called inner().
• outer() initializes a variable called first_num to 1.
• It then calls inner().
• inner() uses the nonlocal keyword to indicate that it wants to
modify the first_num variable from the outer function.
• It then sets first_num to 0 and initializes a new variable called
second_num to 1.
• Finally, it prints the value of second_num.
• After inner() is called, outer() prints the value of first_num.
• Since inner() modified first_num to be 0, the output will be
"outer - first_num is: 0".
• The nonlocal keyword is used to indicate that a variable is not
local to the current function, but is instead defined in an outer
function.
• This allows the inner function to modify the value of the outer
function's variable.

Global Scope
This is perhaps the easiest scope to understand. Whenever a variable is defined
outside any function, it becomes a global variable, and its scope is anywhere within
the program. Which means it can be used by any function.

greeting = "Hello" # Global scope


def greeting_world():
world = "World" # Local scope

Page 25 of 37
print(greeting, world) # Accesses greeting from the global scope

def greeting_name(name):
print(greeting, name) # Accesses greeting from the global scope

greeting_world()
greeting_name("Sumit")
Output:
Hello World
Hello Sumit
Explanation:
• This code defines a variable greeting with the value "Hello".
• It then defines a function greeting_world() that creates a
variable world with the value "World" and prints the concatenation
of greeting and world.
• Another function greeting_name(name) is defined that takes an
argument name and prints the concatenation of greeting and name.
• Finally, the greeting_world() function is called, which prints
"Hello World", and the greeting_name() function is called with the
argument "Sumit", which prints "Hello Sumit".

Scenario 1: Global Scope


Let's say you wanted to be able to change the value of global
variable greeting("Hello") to set a new value ("Hi") for the
greeting, so that greeting_world() prints "Hi World"
Example:
greeting = "Hello"
def change_greeting(new_greeting):
greeting = new_greeting

def greeting_world():
world = "World"
print(greeting, world)

Page 26 of 37
change_greeting("Hi")
greeting_world()
Output:
Hello World
Explanation:
• This code defines a variable greeting with the value "Hello".
• It then defines a function change_greeting that takes a parameter
new_greeting and assigns it to the greeting variable within the
function's scope.
• However, this does not affect the greeting variable outside of the
function's scope.
• The code then defines another function greeting_world that defines
a variable world with the value "World" and prints the greeting
variable followed by the world variable.
• Next, the change_greeting function is called with the argument
"Hi", which assigns "Hi" to the greeting variable within the
function's scope.
• Finally, the greeting_world function is called, which prints the
updated greeting variable ("Hi") followed by the world variable
("World").

This is because when we set the value of greeting to "Hi", it


created a new local variable greeting in the scope
of change_greeting(). It did not change anything for the
global greeting. This is where the global keyword comes in handy.

With global, you're telling Python to use the globally defined


variable instead of locally creating one. To use the keyword, simply
type 'global', followed by the variable name. Let's see this in
action on Scenario 1.

greeting = "Hello"
def change_greeting(new_greeting):
global greeting
greeting = new_greeting

Page 27 of 37
def greeting_world():
world = "World"
print(greeting, world)

change_greeting("Hi")
greeting_world()
Output:
Hi World
Explanation:
• This code defines a global variable greeting with the value
"Hello".
• It also defines a function change_greeting that takes a parameter
new_greeting and changes the value of the global variable greeting
to the value of new_greeting.
• The function greeting_world defines a local variable world with
the value "World" and prints the values of greeting and world.
• The code then calls change_greeting with the argument "Hi", which
changes the value of greeting to "Hi".
• Finally, it calls greeting_world, which prints "Hi World" because
the value of greeting was changed by the previous function call.
• The global keyword is used in change_greeting to indicate that the
variable greeting being referenced is the global variable defined
outside of the function, rather than a local variable with the same
name.

Built-in Scope
When the variable or object is not found in local, global, or enclosing scope, then
Python starts looking for it in the built-in scope. Built-in scopes are one of the widest
scopes that cover all the reserved keywords, built-in functions, exceptions, and
objects. We can call them (keywords, built-in functions, exceptions, and objects)
anywhere within our program without having to define them before use.
Example 1:
print(len([1, 2, 3])) # Uses the len() function from the built-in scope

Page 28 of 37
Example 2:
# Built-in Scope
from math import pi
# pi = 'global pi variable'
def outer():
# pi = 'outer pi variable'
def inner():
# pi = 'inner pi variable'
print(pi)
inner()
outer()
Output:
3.141592653589793
Since, pi is not defined in either local, enclosed or global scope,
the built-in scope is looked up i.e the pi value imported from the
math module. Since the program is able to find the value of pi in
the outermost scope, the following output is obtained.

Example 3:
# Global Scope
x=0
def outer():
# Enclosed Scope
x=1
def inner():
#Local Scope
x=2
print(x)

Page 29 of 37
Let's say you're calling print(x) within inner(), which is a
function nested in outer(). Then Python will first look if "x" was
defined locally within inner(). If not, the variable defined
in outer() will be used. This is the enclosing function. If it also
wasn't defined there, the Python interpreter will go up another
level - to the global scope. Above that, you will only find the
built-in scope, which contains special variables reserved for Python
itself.

Deleting Python function


Till now, we have seen how to delete a variable. Similarly, you can delete a function with the
‘del’ keyword.

>>> def func7():


print("7")
>>> func7()

>>> del func7


>>> func7()

Traceback (most recent call last):


File “<pyshell#137>”, line 1, in <module>
func7()
NameError: name ‘func7’ is not defined
When deleting a function, you don’t need to put parentheses after its name.

Page 30 of 37
Built in Function
Built in functions are the function(s) that are built into Python and can be accessed by a
programmer. These are always available and for using them, we don‟t have to import any
module (file). Python has a small set of built-in functions as most of the functions have been
partitioned to modules.

❖ abs (x)
It returns distance between x and zero, where x is a numeric expression.
Examples:
>>>abs(-45)
45
>>>abs(119L)
119
❖ max( x, y, z, .... )
The max() function is used to return the maximum value for two or more arguments
passed to it. If an iterable like a list is passed as an argument, it will return the largest
item in the iterable.
Example 1:
>>>max(80, 100, 1000)
1000
>>>max(-80, -20, -10)
-10

Example 2:
num_list = [5,10,40,2,15]
max_num_lst = max(num_list)
print('The maximum number in the list:', max_num_lst)
Output:
The maximum number in the list: 40

An example of key argument with a list: max(iterable, key)


For this example of demonstrating the key argument, a list is created that contains
mixed items. The numbers are in the form of strings, float and integer items.

Page 31 of 37
The max() function is used where that list is passed and the key argument is used. The
lambda function is used where each item of the list is converted to int thus max
function will return the maximum value.
Example:
mix_list = [10, '1','100',90, '111','2', 102.5 ]
mx_val=max(mix_list, key=lambda x:int(x))
print("The max value in the list: ",mx_val)
Output:
The max value in the list: 111

If the list was used as in the previous example, an exception would have raised
because the list contains string elements.
An example of multiple iterables with key: max(iterable, *iterables, key)
As mentioned earlier, if two or more iterables are passed the largest argument/iterable
as object is returned.
In this example, two lists are created with six and five elements, respectively. The
max function is used two ways. First, simply sending the two lists as arguments and
the second uses the key argument along with the len() function. See the code and
output:

Example:
lst1 = [5, 7, 'a', 25, 'b', 'c']
lst2 = [10, 'x', 'y', 15, 20]
#Simply passing three lists
print('Without key argument, the maximum list:', max(lst1, lst2))

#Using key argument


print('Using key argument, the maximum list:', max(lst1, lst2, key=len))
Output:
Without key argument, the maximum list: [10, 'x', 'y', 15, 20]
Using key argument, the maximum list: [5, 7, 'a', 25, 'b', 'c']

In the first case, the first items of both lists are compared and the max() function
returned the list with the larger item. In that case, 10 is greater than 5 so the second
list is returned though it has five items.

Page 32 of 37
In the second case, the len() function is used and max returned the list with the larger
number of items. As the first list contains six items, so this is returned and displayed.

❖ min( x, y, z, .... )
It returns the smallest of its arguments; where x, y, and z are numeric
variable/expression.
Examples:
>>> min(80, 100, 1000)
80
>>> min(-80, -20, -10)
-80
❖ cmp( x, y )
It returns the sign of the difference of two numbers:
-1 if x < y, 0 if x == y, or 1 if x > y, where x and y are numeric variable/expression.
Examples:
>>>cmp(80, 100)
-1
>>>cmp(180, 100)
1

❖ divmod (x,y )
Returns both quotient and remainder by division through a tuple, when x is divided by
y; where x & y are variable/expression.
Examples:
>>> divmod (14,5)
(2,4)
>>> divmod (2.7, 1.5)
(1.0, 1.20000)

❖ len (s)
Return the length (the number of items) of an object. The argument may be a
sequence (string, tuple or list) or a mapping (dictionary).
Examples:
>>> a= [1,2,3]
>>>len (a)

Page 33 of 37
3
>>> b= „Hello‟
>>> len (b)
5
❖ range (start, stop[, step])
This is a versatile function to create lists containing arithmetic progressions. It is most
often used in for loops. The arguments must be plain integers. If the step argument is
omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form
returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive,
the last element is the largest start + i * step less than stop; if step is negative, the last
element is the smallest start + i * step greater than stop. Step must not be zero (or else
Value Error is raised).
Examples:
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[ ]
>>> range(1, 0)
[ ]

❖ round( x [, n] )
In order to round the given number to the nearest integer or required precision
(number of digits after decimal point), you may use the Python round() function.
Syntax of using round function
The round() function in Python takes two parameters:
round(number[, ndigits]

Page 34 of 37
Note: If ndigits is not provided then number is rounded to 0 decimal digits.
➢ The round() function returns the rounded value that is closest to the integer to
its given value if ndigits is not provided.
➢ The ndigits specifies the precision after the decimal point.

Example 1:
print("The round value for 10.87 = ",round(10.87))
print("The round value for 10.37 = ",round(10.37))
Output:
The round value for 10.87 = 11
The round value for 10.37 = 10

You can see it returned 11. As such, the rule for rounding the number is any number
greater than or equal to 5 is rounded to the next whole number. That means if the
number to be rounded is 5.5 then after rounding its value will be 6.
If the number is 4, 3, 2, 1 or 0, it remains the same. So, for rounding 5.4 will return 5.

round() with ndigit parameter


In the following example, the round() function is used with both parameters. A float
number is passed with 4 numbers after the decimal point. The ndigit parameter is
given the 2 value so round() will return two digits.
Example 2:
print("The round value for 25.5433 = ",round(25.5433,2))
Output:
The round value for 25.5433 = 25.54

The returned result is 25.54 as next digit is less than 5. What if it was 5 or more, see
next example.
Example 3:
print("The round value for 25.5453 = ",round(25.5453,2))
Output:
The round value for 25.5433 = 25.55

Page 35 of 37
Note: You may see some surprising results as rounding the numbers while using the
round function. For example, round(5.675)) yields 5.67 while it should be 5.68.

Example 4:
>>>round(80.23456, 2)
80.23
>>>round(-100.000056, 3)
-100.0
>>> round (80.23456)
80.0

Example 5: Rounding a float list


float_lst = [10.56, 11.4, 30.456, 40.8, 50.55]
rounded_list = [round(x) for x in float_lst]
print("List before round: ",float_lst)
print("List after round: ",rounded_list)
Output:
List before round: [10.56, 11.4, 30.456, 40.8, 50.55]
List after round: [11, 11, 30, 41, 51]

Example 6: Using precision in the round function for list


float_lst = [10.5678, 11.456545, 30.4561245, 40.845474, 50.55456474]
rounded_list = [round(x,2) for x in float_lst]
print("List before round: ",float_lst)
print("List after round with precision: ",rounded_list)
Output:
List before round: [10.5678, 11.456545, 30.4561245, 40.845474, 50.55456474]
List after round with precision: [10.57, 11.46, 30.46, 40.85, 50.55]

Example 7: Using round function for Fahrenheit to Celsius conversion


Fahrenheit_List = [98, 102, 110, 125]
Celsius_List_simple = map(lambda F: ((5.0/9.0)*(F - 32),2), Fahrenheit_List)
Celsius_List_rounded = map(lambda F: round(((5.0/9.0)*(F - 32)),1),Fahrenheit_List)
print("Celsius List default: ", list(Celsius_List_simple))
print("Celsius List with round function: ", list(Celsius_List_rounded))

Page 36 of 37
Output:
Celsius List default: [(36.66666666666667, 2), (38.88888888888889, 2),
(43.333333333333336, 2), (51.66666666666667, 2)]
Celsius List with round function: [36.7, 38.9, 43.3, 51.7]

Page 37 of 37

You might also like