Function
Function
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.
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.
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.
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)
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)
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"
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
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
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 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")
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.
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 (=).
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.
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.
Page 11 of 37
print (name)
msg(name="Ankur Sharma",35)
Example 1:
def greet(*names):
"""This function greets all
the person in the names tuple."""
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
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
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
Example:
def hello():
print("Hello")
hello()
Output:
Hello
Page 16 of 37
return "Hello Dear"
xyz=hello()
print(xyz)
Output:
Hello Dear
hello("Amit")
Output:
Hello, My name is Amit
Example:
def sum(x,y):
s=x+y
Page 17 of 37
return s
result=sum(5,3)
print("sum=",result)
Output:
sum= 8
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]
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().
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.
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".
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").
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.
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
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))
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.
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
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