0% found this document useful (0 votes)
413 views69 pages

Python Programming Notes - UNIT-I

Python is a high-level, interpreted scripting language developed in the late 1980s by Guido van Rossum. It supports object-oriented programming and is designed to be highly readable. Python has a large standard library and can be used for web development, desktop applications, science/engineering, and more. Python code is first compiled into bytecode then interpreted by the Python virtual machine. It has dynamic typing and supports common data types like numbers, strings, lists, and dictionaries.

Uploaded by

Guru Chowdare M
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
413 views69 pages

Python Programming Notes - UNIT-I

Python is a high-level, interpreted scripting language developed in the late 1980s by Guido van Rossum. It supports object-oriented programming and is designed to be highly readable. Python has a large standard library and can be used for web development, desktop applications, science/engineering, and more. Python code is first compiled into bytecode then interpreted by the Python virtual machine. It has dynamic typing and supports common data types like numbers, strings, lists, and dictionaries.

Uploaded by

Guru Chowdare M
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 69

ANURAG GROUP OF INSTITUTIONS

1.1 INTRODUCTION:

Python is a high-level, interpreted scripting language developed in the late 1980s by


Guido van Rossum at the National Research Institute for Mathematics and Computer Science
in the Netherlands
Python is a general purpose, dynamic, high level, and interpreted programming
language. It supports Object Oriented programming approach to develop applications. It is
simple and easy to learn and provides lots of high-level data structures.
 Python laid its foundation in the late 1980s.
 The implementation of Python was started in the December 1989 by Guido Van
Rossum at CWI in Netherland.
 In February 1991, van Rossum published the code (labeled version 0.9.0) to
alt.sources.
 In 1994, Python 1.0 was released with new features like: lambda, map, filter, and
reduce.
 Python 2.0 added new features like: list comprehensions, garbage collection system.
 On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed
to rectify fundamental flaw of the language.
 ABC programming language is said to be the predecessor of Python language which
was capable of Exception Handling and interfacing with Amoeba Operating System.
 Python is influenced by following programming languages:
 ABC language.
 Modula-3
A Few list of python versions with its released date is given below.
Python Version Released Date

Python 1.0 January 1994

Python 1.5 December 31, 1997

Python 1.6 September 5, 2000

Python 2.0 October 16, 2000

Python 2.5 September 19, 2006

Python 2.6 October 1, 2008

Python 2.7 July 3, 2010

Python 3.0 December 3, 2008

Python 3.3 September 29, 2012

Python 3.4 March 16, 2014

Python 3.5 September 13, 2015

Python 3.6 December 23, 2016

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 1


ANURAG GROUP OF INSTITUTIONS

Python 3.7 June 27, 2018

1.2 FEATURES :

Python provides lots of features that are listed below.

1) Easy to Learn and Use: Python is easy to learn and use. It is developer-friendly and high
level programming language.
2) Expressive Language: Python language is more expressive means that it is more
understandable and readable.
3) Free and Open Source: Python language is freely available at offical web address.The
source-code is also available. Therefore it is open source.
4) High level: Being a high-level language, Python code is quite like English. Looking at it,
you can tell what the code is supposed to do. Also, since it is dynamically-typed, it mandates
indentation. This aids readability.
5) Portable: Python language is also a portable language. for example, if we have python
code for windows and if we want to run this code on other platform such as Linux, Unix and
Mac then we do not need to change it, we can run this code on any platform.
6) Object-Oriented Language: Python supports object oriented language and concepts of
classes and objects come into existence.
7) Extensible: It implies that other languages such as C/C++ can be used to compile the code
and thus it can be used further in our python code.
8) Embeddable or Integrate : It can be easily integrated with languages like C, C++, JAVA
etc.
9) Interpreted Language: Python is an Interpreted Language. because python code is executed
line by line at a time. like other language c, c++, java etc there is no need to compile python
code this makes it easier to debug our code. The source code of python is converted into an
immediate form called byte code.
10) Large Standard Library: Python has a large and broad library and provides rich set of
module and functions for rapid application development.
11) GUI Programming Support: Graphical user interfaces can be developed using Python

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 2


ANURAG GROUP OF INSTITUTIONS

12) Dynamically Typed: Python is dynamically-typed language. That means the type (for
example- int, double, long etc) for a variable is decided at run time not in advance because of
this feature we don’t need to specify the type of variable.

1.3 PYTHON APPLICATIONS:

Python is known for its general purpose nature that makes it applicable in almost each
domain of software development. Python as a whole can be used in any sphere of
development. Here, we are specifying applications areas where python can be applied.
1) Web Applications:
We can use Python to develop web applications. It provides libraries to handle
internet protocols such as HTML and XML, JSON, Email processing, request, beautifulSoup,
Feedparser etc. It also provides Frameworks such as Django, Pyramid, Flask etc to design
and delelop web based applications. Some important developments are: PythonWikiEngines,
Pocoo, PythonBlogSoftware etc.
2) Desktop GUI Applications:
Python provides Tk GUI library to develop user interface in python based application.
Some other useful toolkits wxWidgets, Kivy, pyqt that are useable on several platforms. The
Kivy is popular for writing multitouch applications.
3) Software Development:
Python is helpful for software development process. It works as a support language
and can be used for build control and management, testing etc.
4) Scientific and Numeric:
Python is popular and widely used in scientific and numeric computing. Some useful
library and package are SciPy, Pandas, IPython etc. SciPy is group of packages of
engineering, science and mathematics.
5) Business Applications:
Python is used to build Bussiness applications like ERP and e-commerce systems.
Tryton is a high level application platform.
6) Console Based Application:
We can use Python to develop console based applications. For example: IPython.
7) Audio or Video based Applications:
Python is awesome to perform multiple tasks and can be used to develop multimedia
applications. Some of real applications are: TimPlayer, cplay etc.
8) 3D CAD Applications:
To create CAD application Fandango is a real application which provides full features
of CAD.
9) Enterprise Applications:
Python can be used to create applications which can be used within an Enterprise or
an Organization. Some real time applications are: OpenErp, Tryton, Picalo etc.
10) Applications for Images:
Using Python several application can be developed for image. Applications developed
are: VPython, Gogh, imgSeek etc.

1.4 CREATING & EXECUTING PYTHON :

There are four steps that python takes when you hit return: lexing, parsing, compiling,
and interpreting. Lexing is breaking the line of code you just typed into tokens. The parser
takes those tokens and generates a structure that shows their relationship to each other (in this
case, an Abstract Syntax Tree). The compiler then takes the AST and turns it into one (or

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 3


ANURAG GROUP OF INSTITUTIONS

more) code objects. Finally, the interpreter takes each code object executes the code it
represents.

The Python interpreter performs following tasks to execute a Python program :

 Compiler compiles your source code (the statements in your file) into a format
known as byte code. Compilation is simply a translation step!

 Byte code is a lower level, platform independent, efficient and intermediate


representation of source code. Each of your source statements is translated into a
group of byte code instructions. Compiled code is usually stored in.pyc files , and is
regenerated when the source is updated.

 The Python Virtual Machine(PVM) is the runtime engine of Python; it’s always
present as part of the Python system, and is the component that truly runs your scripts.
The bytecode (.pyc file) is loaded into the Python runtime and interpreted by a Python
Virtual Machine, which is a piece of code that reads each instruction in the
bytecode and executes.

1.5 DATA TYPES :

Variables can hold values of different data types. Python is a dynamically typed
language hence we need not define the type of the variable while declaring it. The interpreter
implicitly binds the value with its type.

Python enables us to check the type of the variable used in the program. Python
provides us the type() function which returns the type of the variable passed.

Consider the following example to define the values of different data types and checking its
type.

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 4


ANURAG GROUP OF INSTITUTIONS

A=10
b="Hi Python"
c = 10.5
print(type(a));
print(type(b));
print(type(c));

Output:
<type 'int'>
<type 'str'>
<type 'float'>

Standard data types

A variable can hold different types of values. For example, a person's name must be stored as
a string whereas its id must be stored as an integer.

Python provides various standard data types that define the storage method on each of them.
The data types defined in Python are given below.

1. Numbers
2. Sequences
1. String
2. List
3. Tuple
4. sets
3. Dictionary

1.5.1 Numbers:

Number stores numeric values. Python creates Number objects when a number is assigned to
a variable. For example;

a = 3 , b = 5 #a and b are number objects

Python supports 4 types of numeric data.

1. int (signed integers like 10, 2, 29, etc.)


2. long (long integers used for a higher range of values like 908090800L, -0x1929292L,
etc.)
3. float (float is used to store floating point numbers like 1.9, 9.902, 15.2, etc.)
4. complex (complex numbers like 2.14j, 2.0 + 2.3j, etc.)

Python allows us to use a lower-case L to be used with long integers. However, we must
always use an upper-case L to avoid confusion.

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 5


ANURAG GROUP OF INSTITUTIONS

A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and
imaginary parts respectively).

1.5.2 Sequences:
In Python, sequence is the generic term for an ordered set. There are several types of
sequences in Python, the following three are the most important.
Strings are a special type of sequence that can only store characters, and they have a
special notation. However, all of the sequence operations described below can also be used
on strings.
Lists are the most versatile sequence type. The elements of a list can be any object,
and lists are mutable - they can be changed. Elements can be reassigned or removed, and
new elements can be inserted.
Tuples are like lists, but they are immutable - they can't be changed.

1.5.2.1 String:

The string can be defined as the sequence of characters represented in the quotation marks. In
python, we can use single, double, or triple quotes to define a string.

String handling in python is a straightforward task since there are various inbuilt functions
and operators provided.

In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".

The operator * is known as repetition operator as the operation "Python " *2 returns "Python
Python ".

The following example illustrates the string handling in python.

str1 = 'hello Ravi' #string str1


str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2

Output:

he
o
hello Ravihello Ravi
hello Ravi how are you

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 6


ANURAG GROUP OF INSTITUTIONS

1.5.2.2 List:
Lists are similar to arrays in C. However; the list can contain data of different types. The
items stored in the list are separated with a comma (,) and enclosed within square brackets [].

We can use slice [:] operators to access the data of the list. The concatenation operator (+)
and repetition operator (*) works with the list in the same way as they were working with the
strings.

Consider the following example.

l1 = [1, "hi", "python", 2]


print l1l[3:]);
print (l1[0:2]);
print (l1);
print (l1+ l1);
print (l1 * 3);

Output:

[2]
[1, 'hi']
[1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2, 1, 'hi', 'python', 2]

1.5.2.3 Tuple:

A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and
enclosed in parentheses ().

A tuple is a read-only data structure as we can't modify the size and value of the items of a
tuple.

Let's see a simple example of the tuple.

t = ("hi", "python", 2)
print (t[1:]);
print (t[0:1]);
print (t);
print (t + t);
print (t * 3);
print (type(t))
t[2] = "hi"; # tuple values are immutable

Output:

('python', 2)

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 7


ANURAG GROUP OF INSTITUTIONS

('hi',)
('hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2, 'hi', 'python', 2)
<type 'tuple'>
Traceback (most recent call last):
File "main.py", line 8, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment

1.5.2.4 Sets:
A set is a collection of data types in Python, same as the list and tuple. However, it is
not an ordered collection of objects. The set is a Python implementation of the set in
Mathematics. A set object has suitable methods to perform mathematical set operations like
union, intersection, difference, etc.

A set object contains one or more items, not necessarily of the same type, which are separated
by comma and enclosed in curly brackets {}.

Syntax:
Set={value1,value2,value3,....valueN}
The following defines a set object.

>>> S1={1, "Bill", 75.50}

A set doesn't store duplicate objects. Even if an object is added more than once inside the
curly brackets, only one copy is held in the set object. Hence, indexing and slicing operations
cannot be done on a set object.

>>> S1={1, 2, 2, 3, 4, 4, 5, 5}
>>> S1
{1, 2, 3, 4, 5}

1.5.3 Dictionary:

Dictionary is an ordered set of a key-value pair of items. It is like an associative array or a


hash table where each key stores a specific value. Key can hold any primitive data type
whereas value is an arbitrary Python object.

The items in the dictionary are separated with the comma and enclosed in the curly braces {}.

Consider the following example.

d = {1:'Ravi', 2:'Raju', 3:'Sudheer',4:'Sekhar'};


print("1st name is "+d[1]);
print("2nd name is "+ d[4]);
print (d);
print (d.keys());
print (d.values());

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 8


ANURAG GROUP OF INSTITUTIONS

Output:

1st name is Ravi


2nd name is Sekhar
{1: 'Ravi', 2: 'Raju', 3: 'Sudheer', 4: 'Sekhar'}
[1, 2, 3, 4]
['Ravi', 'Raju', 'Sudheer', 'Sekhar']

1.6 Operator:

Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

1. Arithmetic operators
2. Comparison or Relational operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Special operators
a. Identity operators
b. Membership operators

1. Arithmetic operators: Arithmetic operators are used to perform mathematical operations


like addition, subtraction, multiplication and division.
OPERATOR DESCRIPTION SYNTAX

+ Addition: adds two operands x+y

- Subtraction: subtracts two operands x-y

* Multiplication: multiplies two operands x*y

/ Division (float): divides the first operand by the second x/y

// Division (floor): divides the first operand by the second x // y

** Exponential: multiply first operand by second operand times x**y

Modulus: returns the remainder when first operand is divided by the


% second x%y

# Examples of Arithmetic Operator


a=9
b=4
add = a + b # Addition of numbers
sub = a – b # Subtraction of numbers
mul = a * b # Multiplication of number
div1 = a / b # Division(float) of number
div2 = a // b # Division(floor) of number
Dept. Of Information Technology Python Programming-UNIT-I - Page No. 9
ANURAG GROUP OF INSTITUTIONS

exp = a ** b # Exponentaial of number


mod = a % b # Modulo of both number

# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(exp)
print(mod)

Output:
13
5
36
2.25
6561
2

2.Relational Operators: Relational operators compares the values. It either


returns Trueor False according to the condition.
OPERATOR DESCRIPTION SYNTAX

> Greater than: True if left operand is greater than the right x>y

< Less than: True if left operand is less than the right x<y

== Equal to: True if both operands are equal x == y

!= Not equal to - True if operands are not equal x != y

Greater than or equal to: True if left operand is greater than or equal to the

>= right x >= y

<= Less than or equal to: True if left operand is less than or equal to the right x <= y

# Examples of Relational Operators


a = 13
b = 33
print(a > b) # a > b is False
print(a < b) # a < b is True
print(a == b) # a == b is False
print(a != b) # a != b is True
Dept. Of Information Technology Python Programming-UNIT-I - Page No. 10
ANURAG GROUP OF INSTITUTIONS

print(a >= b) # a >= b is False


print(a <= b) # a <= b is True

Output:
False
True
False
True
False
True

3.Logical operators: Logical operators perform Logical AND, Logical OR and Logical
NOT operations.
OPERATOR DESCRIPTION SYNTAX

And Logical AND: True if both the operands are true x and y

Or Logical OR: True if either of the operands is true x or y

Not Logical NOT: True if operand is false not x

# Examples of Logical Operator


a = True
b = False
print(a and b) # Print a and b is False
print(a or b) # Print a or b is True
print(not a) # Print not a is False

Output:
False
True
False
4.Bitwise operators: Bitwise operators acts on bits and performs bit by bit operation.
OPERATOR DESCRIPTION SYNTAX

& Bitwise AND x&y

| Bitwise OR x|y

~ Bitwise NOT ~x

^ Bitwise XOR x^y

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 11


ANURAG GROUP OF INSTITUTIONS

>> Bitwise right shift x>>

<< Bitwise left shift x<<

# Examples of Bitwise operators


a = 10
b=4

print(a & b) # Print bitwise AND operation


print(a | b) # Print bitwise OR operation
print(~a) # Print bitwise NOT operation
print(a ^ b) # print bitwise XOR operation
print(a >> 2) # print bitwise right shift operation
print(a << 2) # print bitwise left shift operation

Output:
0
14
-11
14
2
40
5.Assignment operators: Assignment operators are used in Python to assign values to
variables.
a = 5 is a simple assignment operator that assigns the value 5 on the right to the
variable a on the left.
There are various compound operators in Python like a += 5 that adds to the variable
and later assigns the same. It is equivalent to a = a + 5.

Examples of Assignment operators in Python

Operator Example Equivatent to

= x=5 x=5

+= x += 5 x=x+5

-= x -= 5 x=x-5

*= x *= 5 x=x*5

/= x /= 5 x=x/5

%= x %= 5 x=x%5

//= x //= 5 x = x // 5

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 12


ANURAG GROUP OF INSTITUTIONS

**= x **= 5 x = x ** 5

&= x &= 5 x=x&5

|= x |= 5 x=x|5

^= x ^= 5 x=x^5

>>= x >>= 5 x = x >> 5

<<= x <<= 5 x = x << 5

6.Special Operators:
There are some special type of operators like-
1. Identity operators-
is and is not are the identity operators both are used to check if two values are
located on the same part of the memory. Two variables that are equal does not
imply that they are identical.

is True if the operands are identical


is not True if the operands are not identical
# Examples of Identity operators
a1 = 3
b1 = 3
a2 = 'AGI -Information Technology'
b2 = ' AGI -Information Technology'
a3 = [1,2,3]
b3 = [1,2,3]

print(a1 is not b1)


print(a2 is b2)
print(a3 is b3) # Output is False, since lists are mutable.

Output:
False
True
False

6.2 Membership operators-


in and not in are the membership operators; used to test whether a value or variable is in a
sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence

# Examples of Membership operator

x = ' AGI -Information Technology'


y = {3:'a',4:'b'}

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 13


ANURAG GROUP OF INSTITUTIONS

print('G' in x)
print('it-a' not in x)
print('AGI' not in x)
print(3 in y)
print('b' in y)

Output:
True
True
False
True
False

1.7. Expressions:

Expressions are representations of value. They are different from statement in the fact
that statements do something while expressions are representation of value. For example any
string is also an expressions since it represents the value of the string as well.

Python has some advanced constructs through which you can represent values and
hence these constructs are also called expressions.

Python expressions only contain identifiers, literals, and operators. So, what are these?

Identifiers: Any name that is used to define a class, function, variable module, or object is an
identifier.

Literals: These are language-independent terms in Python and should exist independently in
any programming language. In Python, there are the string literals, byte literals, integer
literals, floating point literals, and imaginary literals.

Operators: In Python you can implement the following operations using the corresponding
tokens.

Operator Token

Add +

subtract -

multiply *

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 14


ANURAG GROUP OF INSTITUTIONS

Operator Token

Power **

Integer Division /

remainder %

decorator @

Binary left shift <<

Binary right shift >>

And &

Or \

Binary Xor ^

Binary ones complement ~

Less than <

Greater than >

Less than or equal to <=

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 15


ANURAG GROUP OF INSTITUTIONS

Operator Token

Greater than or equal to >=

Check equality ==

Check not equal !=

Following are a few types of python expressions:

List comprehension

The syntax for list comprehension is shown below:

[ compute(var) for var in iterable ]

For example, the following code will get all the number within 10 and put them in a list.

>>> [x for x in range(10)]


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Dictionary comprehension

This is the same as list comprehension but will use curly braces:

{ k, v for k in iterable }

For example, the following code will get all the numbers within 5 as the keys and will keep
the corresponding squares of those numbers as the values.

>>> {x:x**2 for x in range(5)}


{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Generator expression

The syntax for generator expression is shown below:

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 16


ANURAG GROUP OF INSTITUTIONS

( compute(var) for var in iterable )

For example, the following code will initialize a generator object that returns the values
within 10 when the object is called.

>>> (x for x in range(10))


<generator object <genexpr> at 0x7fec47aee870>
>>> list(x for x in range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Conditional Expressions

You can use the following construct for one-liner conditions:

true_value if Condition else false_value

Example:

>>> x = "1" if True else "2"


>>> x
'1'

1.8 Operator Precedence & Associativity:


The operators with the highest precedence at the top and lowest at the bottom.

Operators Usage
{} Parentheses (grouping)
f(args…) Function call
x[index:index] Slicing
x[index] Subscription
x.attribute Attribute reference
** Exponent
~x Bitwise not
+x, -x Positive, negative
*, /, % Product, division, remainder
+, – Addition, subtraction
<<, >> Shifts left/right
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
in, not in, is, is not, <, <=, >, >=,
<>, !=, == Comparisons, membership, identity
not x Boolean NOT
and Boolean AND
or Boolean OR

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 17


ANURAG GROUP OF INSTITUTIONS

lambda Lambda expression

The associativity is the order in which Python evaluates an expression containing multiple
operators of the same precedence. Almost all operators except the exponent (**) support the
left-to-right associativity.

1.9 Loops Statements:


The programming languages provide various types of loops which are capable of
repeating some specific code several numbers of times.
Before going to discuss about loops, we need to learn range() function concept in
Python.
1.9.1 RANGE() FUNCTION:
Range function is used to iterate the elements in sequence manner
range function is used in for loops. Range function makes programmer to index free while
iterating the loops

RANGE() FUNCTION ARGUMENTS:


Range() function has two set of arguments. They are,

1. SINGLE ARGUMENT RANGE FUNCTION:


SYNTAX:
range (stop)
STOP:
To generate the numbers in sequence up to “stop-1” numbers. It will start from zero.
Ex: range(5)=[0,1,2,3,4]

2. TWO ARGUMENT RANGE FUNCTION:


SYNTAX:
range (start, stop)
START:
Generating the numbers starting from “start”
STOP:
To generate the numbers in sequence up to “stop-1” numbers .
Ex: range(0,5)=[0,1,2,3,4]

3. THREE ARGUMENT RANGE FUNCTION


SYNTAX:
range([start], stop[, step])
START:
Generating the numbers starting from “start”
STOP:
To generate a numbers in sequence up to “stop-1” numbers .
STEP:
difference between each number in the sequence.
Ex: range(1,5,1)=[1,2,3,4]

1.9.2 For:

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 18


ANURAG GROUP OF INSTITUTIONS

The for loop in Python is used to iterate the statements or a part of the program several
times. It is frequently used to traverse the data structures like list, tuple, or dictionary.

The syntax of for loop in python is given below.

for iterating_var in sequence:


statement(s)
It can be used to iterate over iterators and a range. We can use for in loop for user defined
iterators. See this for example.

print("List Iteration") # Iterating over a list


l = [" Anurag", Information ", "Technology"]
for i in l:
print(i)

print("\nTuple Iteration") # Iterating over a tuple (immutable)


t = (" RaviRaju", "Sekhar", "Prudhvi")
for i in t:
print(i)

print("\nString Iteration") # Iterating over a String


s = "KING"
for i in s :
print(i)

print("\nDictionary Iteration") ## Iterating over dictionary


d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
print("%s %d" %(i, d[i]))

Output:
List Iteration
Anurag
Information
Technology

Tuple Iteration
RaviRaju
Sekhar
Prudhvi

String Iteration
K
I
N
G

Dictionary Iteration

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 19


ANURAG GROUP OF INSTITUTIONS
xyz 123
abc 345

Example:2
i=1
n=int(input("Enter the number up to which you want to print the natural numbers?"))
for i in range(0,10):
print(i,end = ' ')
Output:
0 1 2 3 4 5 6 7 8 9

Example:3
for num in range(1,10,2):
print num

output:
1
3
5
7
9

Nested for loop in python:


Python allows us to nest any number of for loops inside a for loop. The inner loop is
executed n number of times for every iteration of the outer loop. The syntax of the nested for
loop in python is given below.
for iterating_var1 in sequence:
for iterating_var2 in sequence:
#block of statements
#Other statements

Example:
n = int(input("Enter the number of rows you want to print?"))
i,j=0,0
for i in range(0,n):
print()
for j in range(0,i+1):
print("*",end="")

Output:
Enter the number of rows you want to print?5
*
**
***
****
*****

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 20


ANURAG GROUP OF INSTITUTIONS

1.9.3 While Loop

Syntax :

while expression:
statement(s)
In Python, all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements.
# prints Hello Anurag 3 Times
count = 0
while (count < 3):
count = count+1
print("Hello Anurag")

Output:
Hello Anurag
Hello Anurag
Hello Anurag

1.10 Decision Making in Python (if , if..else, Nested if, if-elif):

Decision making statements in programming languages decides the direction of flow of


program execution. Decision making statements available in python are:
 if statement
 if..else statements
 nested if statements
 if-elif ladder

1.10.1 if statement:
if statement is the most simple decision making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e if a certain condition is
true then a block of statement is executed otherwise not. Python uses indentation to identify a
block.

Syntax:
if condition:
statement1
statement2

# Here if the condition is true, if block will consider only statement1 to be inside its block.

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 21


ANURAG GROUP OF INSTITUTIONS

Flowchart:

# python program to illustrate If statement

i = 10
if (i > 15):
print ("10 is less than 15")
print ("I am Not in if")

output:
I am Not in if
1.10.2 if-else statement:
The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something else if
the condition is false. Here comes the else statement. We can use the else statement
with if statement to execute a block of code when the condition is false.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Flow chart:

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 22


ANURAG GROUP OF INSTITUTIONS

Example:
# python program to illustrate If else statement
i = 20;
if (i < 15):
print ("i is smaller than 15")
print ("i'm in if Block")
else:
print ("i is greater than 15")
print ("i'm in else Block")
print ("i'm not in if and not in else Block")

Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block

1.10.3 Nested-if
A nested if is an if statement that is the target of another if statement. Nested if
statements means an if statement inside another if statement. Yes, Python allows us to nest if
statements within if statements. i.e, we can place an if statement inside another if statement.

Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Flow chart:-

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 23


ANURAG GROUP OF INSTITUTIONS

Example:
# python program to illustrate nested If statement

i = 10
if (i == 10):
# First if statement
if (i < 15):
print ("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print ("i is smaller than 12 too")
else:
print ("i is greater than 15")

output:

i is smaller than 15
i is smaller than 12 too

1.10.4 if-elif-else ladder:


A user can decide among multiple options. The if statements are executed from the
top down. As soon as one of the conditions controlling the if is true, the statement associated
with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is
true, then the final else statement will be executed.

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 24


ANURAG GROUP OF INSTITUTIONS

Syntax:-
if (condition):
statement
elif (condition):
statement
.
.
else:
statement

Flow Chart:-

Example:
# Python program to illustrate if-elif-else ladder

i = 20
if (i == 10):
print ("i is 10")
elif (i == 15):
print ("i is 15")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")

output:
i is 20

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 25


ANURAG GROUP OF INSTITUTIONS

# Python program to find the largest number among the three input numbers
# take three numbers from user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

if (num1 > num2) and (num1 > num3):


largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3

print("The largest number is",largest)


output:
Enter first number: 10
Enter second number: 12
Enter third number: 14
The largest number is 14.0

A program to calculate the electricity bill, we must understand electricity


charges and rates.
/* 1 - 100 unit - 1.5/-, 101-200 unit - 2.5/-, 201-300 unit - 4/-, 300 - 350 unit - 5/-, above 300
- fixed charge 1500/- for example */

This program can explain as follows- Declare total unit consumed by the customer using the
variable unit. If the unit consumed less or equal to 100 units, calculates the total amount
of consumed =units*1.5. If the unit consumed between 100 to 200 units, calculates the total
amount of consumed=(100*1.5)+(unit-100)*2.5). If unit consumed between 200 to 300
units ,calculates total amount ofconsumed=(100*1.5)+(200-100)*2.5+(units-200)*4. If
unit consumed between 300-350 units ,calculates total amount of consumed=(100*1.5)+
(200-100)*2.5+(300-200)*4+(units-350)*5. If the unit consumed above 350 units, fixed
charge – 1500/=

additional charges
if units<=100 – 25.00, if 100< units and units<=200 – 50.00, if 200 < units and units<=300 –
75.00, if 300<units and units<=350 – 100.00, if units above 350 – No additional charges

#program for calculating electricity bill in Python using and operator

units=int(input("Number of unit consumed: "))


if(units>0 and units<=100):
payAmount=units*1.5
fixedcharge=25.00
elif(units>100 and units<=200):
payAmount=(100*1.5)+(units-100)*2.5
fixedcharge=50.00
elif(units>200 and units<=300):
payAmount=(100*1.5)+(200-100)*2.5+(units-200)*4

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 26


ANURAG GROUP OF INSTITUTIONS

fixedcharge=50.00
elif(units>300):
payAmount=2500;#fixed rate
fixedcharge=75.00
else:
payAmount=0;

Total= payAmount+fixedcharge
print("\nElecticity bill pay=%.2f: " %Total);

output:
Number of unit consumed: 234
Electricity bill pay=586.00:

1.11 Standard I/O operations:

1.11.1 Input():
Developers often have a need to interact with users, either to get data or to provide
some sort of result. Most programs today use a dialog box as a way of asking the user to
provide some type of input. While Python provides us with two inbuilt functions to read the
input from the keyboard.
input ( prompt )
raw_input ( prompt )

input ( ) : This function first takes the input from the user and then evaluates the expression,
which means Python automatically identifies whether user entered a string or a number or
list. If the input provided is not correct then either syntax error or exception is raised by
python. For example –

# Python program showing # a use of input()

val = input("Enter your value: ")


print(val)

output:
Enter your value: 89
89

How the input function works in Python :


 When input() function executes program flow will be stopped until the user has given
an input.
 The text or message display on the output screen to ask a user to enter input value is
optional i.e. the prompt, will be printed on the screen is optional.
 Whatever you enter as input, input function convert it into a string. if you enter an
integer value still input() function convert it into a string. You need to explicitly convert
it into an integer in your code using typecasting.

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 27


ANURAG GROUP OF INSTITUTIONS

Code:
# Program to check input
# type in Python

num = input ("Enter number :")


print(num)
name1 = input("Enter name : ")
print(name1)

# Printing type of input value


print ("Type of number", type(num))
print ("Type of name", type(name1))

output:
Enter number: 1234
1234
Enter name: Raja
Raja
Type of number <class ‘str’>
Type of name <class ‘str’>

raw_input ( ) : This function works in older version (like Python 2.x). This function takes
exactly what is typed from the keyboard, convert it to string and then return it to the variable
in which we want to store. For example –

# Python program showing


# a use of raw_input()

ch = raw_input("Enter your name : ")


print ch

Output:
Enter your name: Ravi Raju Bandlamudi
Ravi Raju Bandlamudi
Here, ch is a variable which will get the string value, typed by user during the execution of
program. Typing of data for the raw_input() function is terminated by enter key. We can
use raw_input() to enter numeric data also.

1.11.2 Output():
In order to print the output, python provides us with a built-in function called print().

Syntax:
print (expression/constant/variable)

Print evaluates the expression before printing it on the monitor. Print statement outputs an
entire (complete) line and then goes to next line for subsequent output (s). To print more than
one item on a single line, comma (,) may be used.
Example:
>>> print ("Hello")

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 28


ANURAG GROUP OF INSTITUTIONS

Hello
>>> print (5.5)
5.5
>>> print (4+6)
10

1.11.3 Python | format() function:

str.format() is one of the string formatting methods in Python3, which allows


multiple substitutions and value formatting. This method lets us concatenate elements within
a string through positional formatting.

Using a Single Formatter :

Formatters work by putting in one or more replacement fields and placeholders


defined by a pair of curly braces { } into a string and calling the str.format(). The value we
wish to put into the placeholders and concatenate with the string passed as parameters into
the format function.

Syntax : { } .format(value)
Parameters :
(value) : Can be an integer, floating point numeric constant, string, characters or even
variables.
Returntype : Returns a formatted string with the value passed as parameter in the
placeholder position.

# Python3 program to demonstarte # the str.format() method

# using format option in a simple string


print ("{}, Best department in Anurag Group of Institutions." .format(" Information
Technology"))

# using format option for a


# value stored in a variable
str = "This article is written in {}"
print (str.format("Python"))

# formatting a string using a numeric constant


print ("Hello, I am {} years old !".format(35))

Output:

Information Technology, Best department in Anurag Group of Institutions.


This article is written in Python
Hello, I am 35 years old!

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 29


ANURAG GROUP OF INSTITUTIONS

Using Multiple Formatters :

Multiple pairs of curly braces can be used while formatting the string. Let’s say if another
variable substitution is needed in sentence, can be done by adding a second pair of curly
braces and passing a second value into the method. Python will replace the placeholders by
values in order.
Syntax :
{ } { } .format(value1, value2)
Parameters :
(value1, value2) : Can be integers, floating point numeric constants, strings, characters and
even variables. Only difference is, the number of values passed as parameters in format()
method must be equal to the number of placeholders created in the string.

# Python program using multiple place holders to demonstrate str.format() method

# Multiple placeholders in format() function

my_string = "{}, is a best {} in {}"


print (my_string.format("Information Technology ", "branch", "Anurag"))

# different datatypes can be used in formatting


print ("Hi ! My name is {} and I am {} years old" .format("RaviRaju", 35))

# The values passed as parameters


# are replaced in order of their entry
print ("This is {} {} {} {}".format("one", "two", "three", "four"))

Output:
Information Technology, is a best branch in Anurag
Hi! My name is RaviRaju and I am 35 years old
This is one two three four

1.12 Functions :
In Python, function is a group of related statements that perform a specific task.

Functions help break our program into smaller and modular chunks. As our program
grows larger and larger, functions make it more organized and manageable.
It avoids repetition and makes code reusable.

Functions are a convenient way to divide your code into useful blocks, allowing us to
order our code, make it more readable, reuse it and save some time. Also functions are a key
way to define interfaces so programmers can share their code.
There are three types of functions in Python:
1. Built-in functions, such as help() to ask for help, min() to get the minimum
value, print()to print an object to the terminal, len(x) or type(y) or
even random.choice([1, 2, 3]), these functions are called predefined functions.

2. User-Defined Functions (UDFs), which are functions that users create to help
them out; And
3. Anonymous functions, which are also called lambda functions

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 30


ANURAG GROUP OF INSTITUTIONS

User defined Functions declaration:


User-defined functions can be defined by using following format.

Defining Functions
A function is defined in Python by the following format:

def functionname(arg1, arg2, ...):


statement1
statement2
...
>>> def functionname(arg1,arg2):
... return arg1+arg2
...
>>> t = functionname(24,24) # Result: 48

If a function takes no arguments, it must still include the parentheses, but without anything in
them:

def functionname():
statement1
statement2
...

The four steps to defining a function in Python are the following:


1. Use the keyword def to declare the function and follow this up with the function name.
2. Add parameters to the function: they should be within the parentheses of the function.
End your line with a colon.
3. Add statements that the functions should execute.
4. End your function with a return statement if the function should output something.
Without the return statement, your function will return an object None.

The arguments in the function definition bind the arguments passed at function
invocation (i.e. when the function is called), which are called actual parameters, to the names
given when the function is defined, which are called formal parameters. The interior of the
function has no knowledge of the names given to the actual parameters; the names of the
actual parameters may not even be accessible (they could be inside another function).

A function can 'return' a value, for example:

def square(x):
return x*x

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 31


ANURAG GROUP OF INSTITUTIONS

A function can define variables within the function body, which are considered 'local' to the
function. The locals together with the arguments comprise all the variables within the scope
of the function. Any names within the function are unbound when the function returns or
reaches the end of the function body.
You can return multiple values as follows:

def first2items(list1):
return list1[0], list1[1]
a, b = first2items(["Hello", "world", "hi", "universe"])
print a + " " + b

1.12.1 Function Calls:


A callable object is an object that can accept some arguments (also called parameters) and
possibly return an object (often a tuple containing multiple objects).
A function is the simplest callable object in Python, but there are others, such as classes or
certain class instances.
Example:

# Define a function `plus()`


def plus(a,b):
return a + b

print(“sum is :” plus(10,50))

output:
sum is: 60

1.12.3 Arguments:
The arguments of a function are defined within the def statement. Like all other
variables in Python, there is no explicit type associated with the function arguments. This fact
is important to consider when making assumptions about the types of data that your function
will receive.
Function arguments can optionally be defined with a default value. The default value will be
assigned in the case that the argument is not present in the call to the function. All arguments
without default values must be listed before arguments with default values in the function
definition.
Declaring Arguments
When calling a function that takes some values for further processing, we need to send some
values as Function Arguments. For example:

>>> def find_max(a,b):


Dept. Of Information Technology Python Programming-UNIT-I - Page No. 32
ANURAG GROUP OF INSTITUTIONS

if(a > b):


print str(a) + " is greater than " + str(b)
elif(b > a):
print str(b) + " is greater than " + str(a)
>>> find_max(30, 45) #Here (30, 45) are the arguments passing for finding max between
this two numbers
The output will be: 45 is greater than 30

1.13 Function arguments in Python:


In Python, user-defined functions can take four different types of arguments. The
argument types and their meanings, however, are pre-defined and can’t be changed. The
following are the four types of arguments and their rules.

 Required arguments
 Default argumengts
 Key word arguments
 Variable length arguments or Arbitrary Arguments

1.13.1 Required Arguments:

We can provide the arguments at the time of function calling. As far as the required
arguments are concerned, these are the arguments which are required to be passed at the time
of function calling with the exact match of their positions in the function call and function
definition. If either of the arguments is not provided in the function call, or the position of the
arguments is changed, then the python interpreter will show the error.

Consider the following example.

Example 1
#the argument name is the required argument to the function func
def func(name):
message = "Hi "+name;
return message;
name = input("Enter the name?")
print(func(name))

Output:

Enter the name?John


Hi John

Example 2
#the function simple_interest accepts three arguments and returns the simple interest accordin
gly
def simple_interest(p,t,r):

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 33


ANURAG GROUP OF INSTITUTIONS

return (p*t*r)/100
p = float(input("Enter the principle amount? "))
r = float(input("Enter the rate of interest? "))
t = float(input("Enter the time in years? "))
print("Simple Interest: ",simple_interest(p,r,t))

Output:
Enter the principle amount? 10000
Enter the rate of interest? 5
Enter the time in years? 2
Simple Interest: 1000.0

Example 3
#the function calculate returns the sum of two arguments a and b
def calculate(a,b):
return a+b
calculate(10) # this causes an error as we are missing a required arguments b.
Output:
TypeError: calculate() missing 1 required positional argument: 'b'

1.13.2 Default Arguments:


Python allows function arguments to have default values. If the function is called without the
argument, the argument gets its default value.

For some functions, you may want to make some parameters optional and use default values
in case the user does not want to provide values for them. This is done with the help of default
argument values. You can specify default argument values for parameters by appending to the
parameter name in the function definition the assignment operator ( =) followed by the default value.
Note that the default argument value should be a constant. More precisely, the default argument value
should be immutable – this is explained in detail in later chapters. For now, just remember this.

Example:
#!/usr/bin/python
# Filename: func_default.py

def say(message, times = 1):


print(message * times)

say('Hello')
say('World', 5)
Output:
$ python func_default.py
Hello
WorldWorldWorldWorldWorld

How It Works:
The function named say is used to print a string as many times as specified. If we
don’t supply a value, then by default, the string is printed just once. We achieve this by
specifying a default argument value of 1 to the parameter times.

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 34


ANURAG GROUP OF INSTITUTIONS

In the first usage of say, we supply only the string and it prints the string once. In the second
usage of say, we supply both the string and an argument 5 stating that we want to say the
string message 5 times.
Important -Only those parameters which are at the end of the parameter list can be
given default argument values i.e. you cannot have a parameter with a default argument value
preceding a parameter without a default argument value in the function’s parameter list.This
is because the values are assigned to the parameters by position. For example, def func(a,
b=5) is valid, but def func(a=5, b) is not valid.

1.13.3 Keyword Arguments:


If you have some functions with many parameters and you want to specify only some
of them, then you can give values for such parameters by naming them – this is
called keyword arguments – we use the name (keyword) instead of the position (which we
have been using all along) to specify the arguments to the function.
There are two advantages – one, using the function is easier since we do not need to worry
about the order of the arguments. Two, we can give values to only those parameters to which
we want to, provided that the other parameters have default argument values.

Example:
#!/usr/bin/python
# Filename: func_key.py

def func(a, b=5, c=10):


print('a is', a, 'and b is', b, 'and c is', c)

func(3, 7)
func(25, c=24)
func(c=50, a=100)
Output:
$ python func_key.py
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50

How It Works:
The function named func has one parameter without a default argument value,
followed by two parameters with default argument values.
In the first usage, func(3, 7), the parameter a gets the value 3, the parameter b gets the
value 7 and c gets the default value of 10.
In the second usage func(25, c=24), the variable a gets the value of 25 due to the
position of the argument. Then, the parameter cgets the value of 24 due to naming i.e.
keyword arguments. The variable b gets the default value of 5.
In the third usage func(c=50, a=100), we use keyword arguments for all specified values.
Notice that we are specifying the value for parameter c before that for a even though a is
defined before c in the function definition.

1.13.4 Arbitrary Arguments or Variable length Arguments:

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 35


ANURAG GROUP OF INSTITUTIONS

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.

Create function with variable length arguments

Following is the syntax to create a function that can take variable length arguments.

def func(*args):

# body of the function

Where, func is the name of the function and *args holds variable length arguments.

Passing multiple arguments

In the following Python program we are recreating the sum function but this time we are
modifying it to take multiple arguments and print them.

Example:
# func
def sum(*args):
print(type(args))
print(args)
sum(10, 20)
sum(10, 20, 30)
sum(10, 20, 30, 40)

Output.

<class 'tuple'>
(10, 20)
<class 'tuple'>
(10, 20, 30)
<class 'tuple'>
(10, 20, 30, 40

So, we can see that the args variable is of type tuple and we are also able to print all
the values that were passed to the function as a tuple.

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 36


ANURAG GROUP OF INSTITUTIONS

Accessing multiple arguments

Since the multiple arguments passed to the function are tuple so we can access them using for
loop.

In the following Python program we are printing out the individual argument.

Example-2:
# func
def sum(*args):
for arg in args:
print(arg)
print('sum(10, 20)')
sum(10, 20)
print('sum(10, 20, 30)')
sum(10, 20, 30)
print('sum(10, 20, 30, 40)')
sum(10, 20, 30, 40)

Output:

sum(10, 20)
10
20
sum(10, 20, 30)
10
20
30
sum(10, 20, 30, 40)
10
20
30
40

So, now that we are able to access the individual argument passed to the function let's
go ahead and modify the sum function that we are working on to return us the sum of the
arguments.

Multiple arguments sum function

Example -3:
# func
def sum(*args):
result = 0
for arg in args:
result = result + arg
return result

print(sum(10, 20)) # 30
print(sum(10, 20, 30)) # 60
print(sum(10, 20, 30, 40)) # 100
Dept. Of Information Technology Python Programming-UNIT-I - Page No. 37
ANURAG GROUP OF INSTITUTIONS

Let's add some checks to the sum function so that we only add arguments that are numbers.
# func
def sum(*args):
result = 0
for arg in args:
if type(arg) in (int, float):
result = result + arg
return result
print(sum(10, 20.10, "hello")) # 30.1

1.14. Scope of variables:

The scopes of the variables depend upon the location where the variable is being declared.
The variable declared in one part of the program may not be accessible to the other parts.

In python, the variables are defined with the two types of scopes.

1. Global variables
2. Local variables

The variable defined outside any function is known to have a global scope whereas the
variable defined inside a function is known to have a local scope.

Consider the following example.

Example 1
def print_message():
message = "hello !! I am going to print a message." # the variable message is local to the fu
nction itself
print(message)
print_message()
print(message) # this will cause an error since a local variable cannot be accessible here.

Output:

hello !! I am going to print a message.


File "/root/PycharmProjects/PythonTest/Test1.py", line 5, in
print(message)
NameError: name 'message' is not defined

Example 2
def calculate(*args):
sum=0
for arg in args:
sum = sum +arg
print("The sum is",sum)

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 38


ANURAG GROUP OF INSTITUTIONS

sum=0
calculate(10,20,30) #60 will be printed as the sum
print("Value of sum outside the function:",sum) # 0 will be printed

Output:

The sum is 60
Value of sum outside the function: 0
1.15 Lambda Functions:
In Python, we use the lambda keyword to declare an anonymous function, which is
why we refer to them as "lambda functions". An anonymous function refers to a function
declared with no name. Although syntactically they look different, lambda functions behave
in the same way as regular functions that are declared using the def keyword.

The anonymous function contains a small piece of code. It simulates inline functions
of C and C++, but it is not exactly an inline function.

The following are the characteristics of Python lambda functions:

 A lambda function can take any number of arguments, but they contain only a single
expression. An expression is a piece of code executed by the lambda function, which
may or may not return any value.
 Lambda functions can be used to return function objects.
 Syntactically, lambda functions are restricted to only a single expression.

1.15.1 Creating a Lambda Function


We use the following syntax to declare a lambda function:
lambda argument(s): expression
As stated above, we can have any number of arguments but only a single expression. The
lambda operator cannot have any statements and it returns a function object that we can
assign to any variable.

For example:
remainder = lambda num: num % 2

print(remainder(5))
Output:
1
In this code the lambda num: num % 2 is the lambda function. The num is the
argument while num % 2 is the expression that is evaluated and the result of the expression is
returned. The expression gets the modulus of the input parameter by 2. Providing 5 as the
parameter, which is divided by 2, we get a remainder of 1.
You should notice that the lambda function in the above script has not been assigned
any name. It simply returns a function object which is assigned to the identifier remainder.
However, despite being anonymous, it was possible for us to call it in the same way that we
call a normal function. The statement:
lambda num: num % 2
Is similar to the following:
def remainder(num):
return num % 2

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 39


ANURAG GROUP OF INSTITUTIONS

Here is another example of a lambda function:


product = lambda x, y : x * y

print(product(2, 3))
Output
6

1.15.2 Why use lambda functions?

The main role of the lambda function is better described in the scenarios when we use
them anonymously inside another function. In python, the lambda function can be used as an
argument to the higher order functions as arguments. Lambda functions are also used in the
scenario where we need a Consider the following example.

Example 1:
#the function table(n) prints the table of n
def table(n):
return lambda a:a*n; # a will contain the iteration variable i and a multiple of n is returne
d at each function call
n = int(input("Enter the number?"))
b = table(n) #the entered number is passed into the function table. b will contain a lambda fun
ction which is called again and again with the iteration variable i
for i in range(1,11):
print(n,"X",i,"=",b(i)); #the lambda function b is called with the iteration variable i,

Output:

Enter the number?10


10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100

Example 2

Use of lambda function with filter

#program to filter out the list which contains odd numbers

List = {1,2,3,4,10,123,22}
Oddlist = list(filter(lambda x:(x%3 == 0),List)) # the list contains all the items of the list for
which the lambda function evaluates to true
Dept. Of Information Technology Python Programming-UNIT-I - Page No. 40
ANURAG GROUP OF INSTITUTIONS

print(Oddlist)

Output:

[3, 123]

Example 3

Use of lambda function with map

#program to triple each number of the list using map


List = {1,2,3,4,10,123,22}
new_list = list(map(lambda x:x*3,List)) # this will return the triple of each item of the list an
d add it to new_list
print(new_list)

Output:

[3, 6, 9, 12, 30, 66, 369]

1.16 Recursive Functions:


A function that calls itself is a recursive function. This method is used when a certain
problem is defined in terms of itself. Although this involves iteration, using an iterative
approach to solve such a problem can be tedious. The recursive approach provides a very
concise solution to a seemingly complex problem. It looks glamorous but can be difficult to
comprehend!

Overview of how recursive function works

1. Recursive function is called by some external code.


2. If the base condition is met then the program do something meaningful and exits.
3. Otherwise, function does some required processing and then call itself to continue
recursion.

The most popular example of recursion is the calculation of the factorial. Mathematically
the factorial is defined as: n! = n * (n-1)!

We use the factorial itself to define the factorial. Hence, this is a suitable case to write
a recursive function. Let us expand the above definition for the calculation of the factorial
value of 5.

5! = 5 X 4!
5 X4 X 3!
5 X4 X 3 X 2!
5 X4 X 3 X 2 X 1!
5 X4 X 3 X 2 X 1
= 120

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 41


ANURAG GROUP OF INSTITUTIONS

While we can perform this calculation using a loop, its recursive function involves
successively calling it by decrementing the number until it reaches 1. The following is a
recursive function to calculate the factorial.

Example: Recursive Function


def factorial(n):
if n == 1:
print(n)
return 1
else:
print (n,'*', end=' ')
return n * factorial(n-1)
The above recursive function can be called as below.

>>> factorial(5)
5*4*3*2*1
120

When the factorial function is called with 5 as argument, successive calls to the same
function are placed, while reducing the value of 5. Functions start returning to their earlier
call after the argument reaches 1. The return value of the first call is a cumulative product of
the return values of all calls.

Example -2:
Problem Description
The program takes two numbers and finds the GCD of two numbers using recursion.
Program/Source Code
Here is source code of the Python Program to find the GCD of two numbers using recursion.
The program output is also shown below.
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
GCD=gcd(a,b)
print("GCD is: ")
print(GCD)
Program Explanation
1. User must enter two numbers.
2. The two numbers are passed as arguments to a recursive function.
3. When the second number becomes 0, the first number is returned.
4. Else the function is recursively called with the arguments as the second number and the
remainder when the first number is divided by the second number.

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 42


ANURAG GROUP OF INSTITUTIONS

5. The first number is then returned which is the GCD of the two numbers.
6. The GCD is then printed.
Runtime Test Cases

Case 1:
Enter first number:5
Enter second number:15
GCD is:
5

Case 2:
Enter first number:30
Enter second number:12
GCD is:
6

Example-3:
Problem Description
The program takes the number of terms and determines the fibonacci series using recursion
upto that term.
Program/Source Code
Here is source code of the Python Program to find the fibonacci series using recursion. The
program output is also shown below.
def fibonacci(n):
if(n <= 1):
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
n = int(input("Enter number of terms:"))
print("Fibonacci sequence:")
for i in range(n):
print fibonacci(i),
Program Explanation
1. User must enter the number of terms and store it in a variable.
2. The number is passed as an argument to a recursive function.
3. The base condition is that the number has to be lesser than or equal to 1.
4. Otherwise the function is called recursively with the argument as the number minus 1
added to the function called recursively with the argument as the number minus 2.
5. The result is returned and a for statement is used to print the fibonacci series.
Runtime Test Cases

Case 1:
Enter number of terms:5
Fibonacci sequence:
01123
Dept. Of Information Technology Python Programming-UNIT-I - Page No. 43
ANURAG GROUP OF INSTITUTIONS

Case 2:
Enter number of terms:7
Fibonacci sequence:
0112358

1.16.2 Advantages of Python Recursion


1. Reduces unnecessary calling of function, thus reduces length of program.
2. Very flexible in data structure like stacks, queues, linked list and quick sort.
3. Big and complex iterative solutions are easy and simple with Python recursion.
4. Algorithms can be defined recursively making it much easier to visualize and prove.

1.16.3 Disadvantages of Python Recursion


1. Slow.
2. Logical but difficult to trace and debug.
3. Requires extra storage space. For every recursive calls separate memory is allocated
for the variables.
4. Recursive functions often throw a Stack Overflow E

1.17 Python Modules:

A python module can be defined as a python program file which contains a python
code including python functions, class, or variables. In other words, we can say that our
python code file saved with the extension (.py) is treated as the module. We may have a
runnable code inside the python module.

Modules in Python provides us the flexibility to organize the code in a logical way.

To use the functionality of one module into another, we must have to import the
specific module.

Example
In this example, we will create a module named as file.py which contains a function func that
contains a code to print some message on the console.
Let's create the module named as file.py.
#displayMsg prints a message to the name being passed.
def displayMsg(name)
print("Hi "+name);

Here, we need to include this module into our main module to call the method displayMsg()
defined in the module named file.

1.17.1 Loading the module in our python code

We need to load the module in our python code to use its functionality. Python provides two
types of statements as defined below.
 The import statement
 The from-import statement

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 44


ANURAG GROUP OF INSTITUTIONS

1.17.1.1 The import statement

The import statement is used to import all the functionality of one module into another. Here,
we must notice that we can use the functionality of any python source file by importing that
file as the module into another python source file.

We can import multiple modules with a single import statement, but a module is loaded once
regardless of the number of times, it has been imported into our file.

The syntax to use the import statement is given below.

import module1,module2,........ module n

Hence, if we need to call the function displayMsg() defined in the file file.py, we have to
import that file as a module into our module as shown in the example below.

Example:
import file;
name = input("Enter the name?")
file.displayMsg(name)

Output:

Enter the name?John


Hi John

1.17.1.2 The from-import statement

Instead of importing the whole module into the namespace, python provides the flexibility to
import only the specific attributes of a module. This can be done by using from? import
statement. The syntax to use the from-import statement is given below.

from < module-name> import <name 1>, <name 2>..,<name n>

Consider the following module named as calculation which contains three functions as
summation, multiplication, and divide.

calculation.py:

#place the code in the calculation.py


def summation(a,b):
return a+b
def multiplication(a,b):
return a*b;
def divide(a,b):
return a/b;

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 45


ANURAG GROUP OF INSTITUTIONS

Main.py:

from calculation import summation


#it will import only the summation() from calculation.py
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
print("Sum = ",summation(a,b)) #we do not need to specify the module name while accessin
g summation()

Output:

Enter the first number10


Enter the second number20
Sum = 30

The from...import statement is always better to use if we know the attributes to be imported
from the module in advance. It doesn't let our code to be heavier. We can also import all the
attributes from a module by using *.

Consider the following syntax.

from <module> import *

1.17.2 Renaming a module

Python provides us the flexibility to import some module with a specific name so that we can
use this name to use that module in our python source file.

The syntax to rename a module is given below.

import <module-name> as <specific-name>

Example
#the module calculation of previous example is imported in this example as cal.
import calculation as cal;
a = int(input("Enter a?"));
b = int(input("Enter b?"));
print("Sum = ",cal.summation(a,b))

Output:

Enter a?10
Enter b?20
Sum = 30

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 46


ANURAG GROUP OF INSTITUTIONS

1.17.3 Using dir() function

The dir() function returns a sorted list of names defined in the passed module. This list
contains all the sub-modules, variables and functions defined in this module.

Consider the following example.

Example
import json

List = dir(json)

print(List)

Output:

['JSONDecoder', 'JSONEncoder', '__all__', '__author__', '__builtins__', '__cached__',


'__doc__',
'__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__',
'_default_decoder', '_default_encoder', 'decoder', 'dump', 'dumps', 'encoder', 'load', 'loads',
'scanner']

1.17.4 The reload() function

As we have already stated that, a module is loaded once regardless of the number of times it
is imported into the python source file. However, if you want to reload the already imported
module to re-execute the top-level code, python provides us the reload() function. The syntax
to use the reload() function is given below.

reload(<module-name>)

for example, to reload the module calculation defined in the previous example, we must use
the following line of code.

reload(calculation)

Python packages

The packages in python facilitate the developer with the application development
environment by providing a hierarchical directory structure where a package contains sub-
packages, modules, and sub-modules. The packages are used to categorize the application
level code efficiently.

Let's create a package named Employees in your home directory. Consider the following
steps.

1. Create a directory with name Employees on path /home.

2. Create a python source file with name ITEmployees.py on the path /home/Employees.
Dept. Of Information Technology Python Programming-UNIT-I - Page No. 47
ANURAG GROUP OF INSTITUTIONS

ITEmployees.py

def getITNames():
List = ["John", "David", "Nick", "Martin"]
return List;

3. Similarly, create one more python file with name BPOEmployees.py and create a function
getBPONames().

4. Now, the directory Employees which we have created in the first step contains two python
modules. To make this directory a package, we need to include one more file here, that is
__init__.py which contains the import statements of the modules defined in this directory.

__init__.py

from ITEmployees import getITNames


from BPOEmployees import getBPONames

5. Now, the directory Employees has become the package containing two python modules.
Here we must notice that we must have to create __init__.py inside a directory to convert this
directory to a package.

6. To use the modules defined inside the package Employees, we must have to import this in
our python source file. Let's create a simple python source file at our home directory (/home)
which uses the modules defined in this package.

Test.py

import Employees
print(Employees.getNames())

Output:

['John', 'David', 'Nick', 'Martin']

We can have sub-packages inside the packages. We can nest the packages up to any
level depending upon the application requirements.

The following image shows the directory structure of an application Library


management system which contains three sub-packages as Admin, Librarian, and Student.
The sub-packages contain the python modules.

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 48


ANURAG GROUP OF INSTITUTIONS

1.18 DOCSTRING:
Python documentation strings (or docstrings) provide a convenient way of
associating documentation with Python modules, functions, classes, and methods.

Python Docstring is the documentation string which is string literal, and it occurs in
the class, module, function or method definition, and it is written as a first statement.
Docstrings are accessible from the doc attribute for any of the Python object and also with the
built-in help() function can come in handy.
Also, Docstrings are great for the understanding the functionality of the larger part of
the code, i.e., the general purpose of any class, module or function whereas the comments are
used for code, statement, and expressions which tend to be small. They are a descriptive text
written by a programmer mainly for themselves to know what the line of code or expression
does. It is an essential part that documenting your code is going to serve well enough for
writing clean code and well-written programs. Though already mentioned there are no
standard and rules for doing so.
There are two forms of writing a Docstring: one-line Docstrings and multi-line
Docstrings. These are the documentation that is used by Data Scientists/programmers in their
projects.
1.18.1 One-line Docstrings
The one-line Docstrings are the Docstrings which fits all in one line. You can use one of the
quotes, i.e., triple single or triple double quotes and opening quotes and closing quotes need
to be the same. In the one-line Docstrings, closing quotes are in the same line as with the
opening quotes. Also, the standard convention is to use the triple-double quotes.

Example:
def square(a):
'''Returns argument a is squared.'''
return a**a

print (square.__doc__)

help(square)
Returns argument a is squared.

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 49


ANURAG GROUP OF INSTITUTIONS
Help on function square in module __main__:

square(a)
Returns argument a is squared.
Here in the above code, you get the printed result:
Returns argument a is squared.
Help on function square in module __main__:

square(a)
Returns argument a is squared.
In the above Docstrings, you can observe that:
The line begins with a capital letter, i.e., R in our case and end with a period(".").
The closing quotes are on the same line as the opening quotes. This looks better for
one-liners.
There's no blank line either before or after the Docstring. It is good practice.
The above line in quotes is more of command than a description which ends with a
period sign at last.

1.18.2 Multi-line Docstrings


Multi-line Docstrings also contains the same string literals line as in One-line
Docstrings, but it is followed by a single blank along with the descriptive text.
The general format for writing a Multi-line Docstring is as follows:
Example:
def some_function(argument1):
"""Summary or Description of the Function

Parameters:
argument1 (int): Description of arg1

Returns:
int:Returning value

"""

return argument1

print(some_function.__doc__)

Summary or Description of the Function

Parameters:
argument1 (int): Description of arg1

Returns:
int:Returning value

The above code outputs:


Summary or Description of the Function

Parameters:
argument1 (int): Description of arg1

Returns:
int: Returning value
Dept. Of Information Technology Python Programming-UNIT-I - Page No. 50
ANURAG GROUP OF INSTITUTIONS

Example:
Let's look at the example which can show how the multi-line strings can be used in
detail:

def string_reverse(str1):
""" Returns the reversed String.

Parameters:
str1 (str):The string which is to be reversed.

Returns:
reverse(str1):The string which gets reversed.

"""
reverse_str1 = ''
i = len(str1)
while i > 0:
reverse_str1 += str1[ i - 1 ]
i = i- 1
return reverse_str1
print(string_reverse('projkal998580'))
output:
085899lakjorp
You can see above that the summary line is on one line and is also separated from
other content by a single blank line. This convention needs to be followed which is useful for
the automatic indexing tools.

1.18.3 Popular Docstring Formats


There are many Docstrings format available, but it is always better to use the formats
which are easily recognized by the Docstring parser and also to fellow Data Scientist/
programmers. There is no any rules and regulations for selecting a Docstring format, but the
consistency of choosing the same format over the project is necessary. Also, It is preferred
for you to use the formatting type which is mostly supported by Sphinx.

The most common formats used are listed below.

Formatting Type Description

NumPy/SciPy Combination of reStructured and GoogleDocstrings and supported by


docstrings Sphinx

Pydoc Standard documentation module for Python and supported by Sphinx

Render Epytext as series of HTML documents and a tool for generating


Epydoc
API documentation for Python modules based on their Docstrings

Google Docstrings Google's Style

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 51


ANURAG GROUP OF INSTITUTIONS

1.19 Python Built-In Functions

Function Description

abs() Returns the absolute value of a number

all() Returns True if all items in an iterable object are true

any() Returns True if any item in an iterable object is true

ascii() Returns a readable version of an object. Replaces none-ascii characters


with escape character

bin() Returns the binary version of a number

bool() Returns the boolean value of the specified object

bytearray() Returns an array of bytes

bytes() Returns a bytes object

callable() Returns True if the specified object is callable, otherwise False

chr() Returns a character from the specified Unicode code.

classmethod() Converts a method into a class method

compile() Returns the specified source as an object, ready to be executed

complex() Returns a complex number

delattr() Deletes the specified attribute (property or method) from the specified
object

dict() Returns a dictionary (Array)

dir() Returns a list of the specified object's properties and methods

divmod() Returns the quotient and the remainder when argument1 is divided by
argument2

enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate object

eval() Evaluates and executes an expression

exec() Executes the specified code (or object)

filter() Use a filter function to exclude items in an iterable object

float() Returns a floating point number

format() Formats a specified value

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 52


ANURAG GROUP OF INSTITUTIONS

frozenset() Returns a frozenset object

getattr() Returns the value of the specified attribute (property or method)

globals() Returns the current global symbol table as a dictionary

hasattr() Returns True if the specified object has the specified attribute
(property/method)

hash() Returns the hash value of a specified object

help() Executes the built-in help system

hex() Converts a number into a hexadecimal value

id() Returns the id of an object

input() Allowing user input

int() Returns an integer number

isinstance() Returns True if a specified object is an instance of a specified object

issubclass() Returns True if a specified class is a subclass of a specified object

iter() Returns an iterator object

len() Returns the length of an object

list() Returns a list

locals() Returns an updated dictionary of the current local symbol table

map() Returns the specified iterator with the specified function applied to each
item

max() Returns the largest item in an iterable

memoryview() Returns a memory view object

min() Returns the smallest item in an iterable

next() Returns the next item in an iterable

object() Returns a new object

oct() Converts a number into an octal

open() Opens a file and returns a file object

ord() Convert an integer representing the Unicode of the specified character

pow() Returns the value of x to the power of y

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 53


ANURAG GROUP OF INSTITUTIONS

print() Prints to the standard output device

property() Gets, sets, deletes a property

range() Returns a sequence of numbers, starting from 0 and increments by 1 (by


default)

repr() Returns a readable version of an object

reversed() Returns a reversed iterator

round() Rounds a numbers

set() Returns a new set object

setattr() Sets an attribute (property/method) of an object

slice() Returns a slice object

sorted() Returns a sorted list

@staticmethod() Converts a method into a static method

str() Returns a string object

sum() Sums the items of an iterator

tuple() Returns a tuple

type() Returns the type of an object

vars() Returns the __dict__ property of an object

zip() Returns an iterator, from two or more iterators

1. abs()
The abs() is one of the most popular Python built-in functions, which returns the absolute
value of a number. A negative value’s absolute is that value is positive.
>>> abs(-7)
7
>>> abs(7)
7
>>> abs(0)

2. all()
The all() function takes a container as an argument. This Built in Functions returns True if all
values in a python iterable have a Boolean value of True. An empty value has a Boolean
value of False.
>>> all({'*','',''})
False
>>> all([' ',' ',' '])
True
Dept. Of Information Technology Python Programming-UNIT-I - Page No. 54
ANURAG GROUP OF INSTITUTIONS

3. any()
Like all(), it takes one argument and returns True if, even one value in the iterable has a
Boolean value of True.
>>> any((1,0,0))
True
>>> any((0,0,0))
False

4. ascii()
It is important Python built-in functions, returns a printable representation of a python
object (like a string or a Python list). Let’s take a Romanian character.
>>> ascii('ș')
“‘\\u0219′”
Since this was a non-ASCII character in python, the interpreter added a backslash (\) and
escaped it using another backslash.
>>> ascii('ușor')
“‘u\\u0219or'”
Let’s apply it to a list.
>>> ascii(['s','ș'])
“[‘s’, ‘\\u0219’]”

5. bin()
bin() converts an integer to a binary string. We have seen this and other functions in our
article on Python Numbers.
>>> bin(7)
‘0b111’
We can’t apply it on floats, though.
>>> bin(7.0)
Traceback (most recent call last):
File “<pyshell#20>”, line 1, in <module>
bin(7.0)
TypeError: ‘float’ object cannot be interpreted as an integer

6. bool()
bool() converts a value to Boolean.
>>> bool(0.5)
True
>>> bool('')
False
>>> bool(True)
True

7. bytearray()
bytearray() returns a python array of a given byte size.
>>> a=bytearray(4)
>>> a
bytearray(b’\x00\x00\x00\x00′)
>>> a.append(1)
>>> a
bytearray(b’\x00\x00\x00\x00\x01′)

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 55


ANURAG GROUP OF INSTITUTIONS

>>> a[0]=1
>>> a
bytearray(b’\x01\x00\x00\x00\x01′)
>>> a[0]
1
Let’s do this on a list.
>>> bytearray([1,2,3,4])
bytearray(b’\x01\x02\x03\x04′)

8. bytes():
bytes() returns an immutable bytes object.
>>> bytes(5)
b’\x00\x00\x00\x00\x00′
>>> bytes([1,2,3,4,5])
b’\x01\x02\x03\x04\x05′
>>> bytes('hello','utf-8')
b’hello’
Here, utf-8 is the encoding.
Both bytes() and bytearray() deal with raw data, but bytearray() is mutable, while bytes() is
immutable.
>>> a=bytes([1,2,3,4,5])
>>> a
b’\x01\x02\x03\x04\x05′
>>> a[4]=
3
Traceback (most recent call last):
File “<pyshell#46>”, line 1, in <module>
a[4]=3
TypeError: ‘bytes’ object does not support item assignment
Let’s try this on bytearray().
>>> a=bytearray([1,2,3,4,5])
>>> a
bytearray(b’\x01\x02\x03\x04\x05′)
>>> a[4]=3
>>> a
bytearray(b’\x01\x02\x03\x04\x03′)

9. callable()
callable() tells us if an object can be called.
>>> callable([1,2,3])
False
>>> callable(callable)
True
>>> callable(False)
False
>>> callable(list)
True
A function is callable, a list is not. Even the callable() python Built In function is callable.

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 56


ANURAG GROUP OF INSTITUTIONS

10. chr()
chr() Built In function returns the character in python for an ASCII value.
>>> chr(65)
‘A’
>>> chr(97)
‘a’
>>> chr(9)
‘\t’
>>> chr(48)
‘0’

11. classmethod()
classmethod() returns a class method for a given method.
>>> class fruit:
def sayhi(self):
print("Hi, I'm a fruit")

>>> fruit.sayhi=classmethod(fruit.sayhi)
>>> fruit.sayhi()
Hi, I’m a fruit
When we pass the method sayhi() as an argument to classmethod(), it converts it into a
python class method one that belongs to the class. Then, we call it like we would call any
static method in python without an object.

12. compile()
compile() returns a Python code object. We use Python in built function to convert a string
code into object code.
>>> exec(compile('a=5\nb=7\nprint(a+b)','','exec'))
12
Here, ‘exec’ is the mode. The parameter before that is the filename for the file form which
the code is read.
Finally, we execute it using exec().

13. complex()
complex() function creates a complex number. We have seen this is our article on Python
Numbers.
>>> complex(3)
(3+0j)
>>> complex(3.5)
(3.5+0j)
>>> complex(3+5j)
(3+5j)

14. delattr()
delattr() takes two arguments- a class, and an attribute in it. It deletes the attribute.
>>> class fruit:
size=7

>>> orange=fruit()
>>> orange.size

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 57


ANURAG GROUP OF INSTITUTIONS

7
>>> delattr(fruit,'size')
>>> orange.size
Traceback (most recent call last):
File “<pyshell#95>”, line 1, in <module>
orange.size
AttributeError: ‘fruit’ object has no attribute ‘size’

15. dict()
dict(), as we have seen it, creates a python dictionary.
>>> dict()
{}
>>> dict([(1,2),(3,4)])
{1: 2, 3: 4}
This was about dict() Python Built In function

16. dir()
dir() returns an object’s attributes.
>>> class fruit:
size=7
shape='round'
>>> orange=fruit()
>>> dir(orange)
[‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’,
‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’,
‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’,
‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__weakref__’, ‘shape’, ‘size’]

17. divmod()
divmod() in Python built-in functions, takes two parameters, and returns a tuple of their
quotient and remainder. In other words, it returns the floor division and the modulus of the
two numbers.
>>> divmod(3,7)
(0, 3)
>>> divmod(7,3)
(2, 1)
If you encounter any doubt in Python Built-in Function, Please Comment.

18. enumerate()
This Python Built In function returns an enumerate object. In other words, it adds a counter to
the iterable.
>>> for i in enumerate(['a','b','c']):
print(i)
(0, ‘a’)
(1, ‘b’)
(2, ‘c’)

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 58


ANURAG GROUP OF INSTITUTIONS

19. eval()
This Function takes a string as an argument, which is parsed as an expression.
>>> x=7
>>> eval('x+7')
14
>>> eval('x+(x%2)')
8

20. exec()
exec() runs Python code dynamically.
>>> exec('a=2;b=3;print(a+b)')
5
>>> exec(input("Enter your program"))
Enter your programprint(2+3)
5

21. filter()
Like we’ve seen in python Lambda Expressios, filter() filters out the items for which the
condition is True.
>>> list(filter(lambda x:x%2==0,[1,2,0,False]))
[2, 0, False]

22. float()
This Python Built In function converts an int or a compatible value into a float.
>>> float(2)
2.0
>>> float('3')
3.0
>>> float('3s')
Traceback (most recent call last):
File “<pyshell#136>”, line 1, in <module>
float(‘3s’)
ValueError: could not convert string to float: ‘3s’
>>> float(False)
0.0
>>> float(4.7)
4.7

23. format()
We have seen this Python built-in function, one in our lesson on Python Strings.
>>> a,b=2,3
>>> print("a={0} and b={1}".format(a,b))
a=2 and b=3
>>> print("a={a} and b={b}".format(a=3,b=4))
a=3 and b=4

24. frozenset()
frozenset() returns an immutable frozenset object.
>>> frozenset((3,2,4))
frozenset({2, 3, 4})

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 59


ANURAG GROUP OF INSTITUTIONS

Read Python Sets and Booleans for more on frozenset.

25. getattr()
getattr() returns the value of an object’s attribute.
>>> getattr(orange,'size')
7

26. globals()
This Python built-in functions, returns a dictionary of the current global symbol table.
>>> globals()
{‘__name__’: ‘__main__’, ‘__doc__’: None, ‘__package__’: None, ‘__loader__’: <class
‘_frozen_importlib.BuiltinImporter’>, ‘__spec__’: None, ‘__annotations__’: {},
‘__builtins__’: <module ‘builtins’ (built-in)>, ‘fruit’: <class ‘__main__.fruit’>, ‘orange’:
<__main__.fruit object at 0x05F937D0>, ‘a’: 2, ‘numbers’: [1, 2, 3], ‘i’: (2, 3), ‘x’: 7, ‘b’: 3}

27. hasattr()
Like delattr() and getattr(), hasattr() Python built-in functions, returns True if the object has
that attribute.
>>> hasattr(orange,'size')
True
>>> hasattr(orange,'shape')
True
>>> hasattr(orange,'color')
False

28. hash()
hash() function returns the hash value of an object. And in Python, everything is an object.
>>> hash(orange)
6263677
>>> hash(orange)
6263677
>>> hash(True)
1
>>> hash(0)
0
>>> hash(3.7)
644245917
>>> hash(hash)
25553952
This was all about hash() Python In Built function

29. help()
To get details about any module, keyword, symbol, or topic, we use the help() function.
>>> help()

Welcome to Python 3.6's help utility!

If this is your first time using Python, you should definitely check out the tutorial on the
Internet at http://docs.python.org/3.6/tutorial/.

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 60


ANURAG GROUP OF INSTITUTIONS

Enter the name of any module, keyword, or topic to get help on writing Python programs and
using Python modules. To quit this help utility and return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type "modules",


"keywords", "symbols", or "topics". Each module also comes with a one-line summary of
what it does; to list the modules whose name or summary contain a given string such as
"spam", type "modules spam".

help> map
Help on class map in module builtins:
class map(object)
| map(func, *iterables) --> map object
|
| Make an iterator that computes the function using arguments from
| each of the iterables. Stops when the shortest iterable is exhausted.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
help> You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)". Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.
>>>

30. hex()
Hex() Python built-in functions, converts an integer to hexadecimal.
>>> hex(16)
‘0x10’
>>> hex(False)
‘0x0’

31. id() Function

id() returns an object’s identity.


>>> id(orange)
100218832

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 61


ANURAG GROUP OF INSTITUTIONS

>>> id({1,2,3})==id({1,3,2})
True

32. input()
Input() Python built-in functions, reads and returns a line of string.
>>> input("Enter a number")
Enter a number7
‘7’
Note that this returns the input as a string. If we want to take 7 as an integer, we need to apply
the int() function to it.
>>> int(input("Enter a number"))
Enter a number7
7

33. int()
int() converts a value to an integer.
>>> int('7')
7

34. isinstance()
We have seen this one in previous lessons. isinstance() takes a variable and a class as
arguments. Then, it returns True if the variable belongs to the class. Otherwise, it returns
False.
>>> isinstance(0,str)
False
>>> isinstance(orange,fruit)
True

35. issubclass()
This Python Built In function takes two arguments- two python classes. If the first class is a
subclass of the second, it returns True. Otherwise, it returns False.
>>> issubclass(fruit,fruit)
True
>>> class fruit:
pass
>>> class citrus(fruit):
pass
>>> issubclass(fruit,citrus)
False

36. iter()
Iter() Python built-in functions, returns a python iterator for an object.
>>> for i in iter([1,2,3]):
print(i)
1
2
3

37. len()
We’ve seen len() so many times by now. It returns the length of an object.

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 62


ANURAG GROUP OF INSTITUTIONS

>>> len({1,2,2,3})
3
Here, we get 3 instead of 4, because the set takes the value ‘2’ only once.

38. list()
list() creates a list from a sequence of values.
>>> list({1,3,2,2})
[1, 2, 3]

39. locals()
This function returns a dictionary of the current local symbol table.
>>> locals()
{‘__name__’: ‘__main__’, ‘__doc__’: None, ‘__package__’: None, ‘__loader__’: <class
‘_frozen_importlib.BuiltinImporter’>, ‘__spec__’: None, ‘__annotations__’: {},
‘__builtins__’: <module ‘builtins’ (built-in)>, ‘fruit’: <class ‘__main__.fruit’>, ‘orange’:
<__main__.fruit object at 0x05F937D0>, ‘a’: 2, ‘numbers’: [1, 2, 3], ‘i’: 3, ‘x’: 7, ‘b’: 3,
‘citrus’: <class ‘__main__.citrus’>}

40. map()
Like filter(), map() Python built-in functions, takes a function and applies it on an iterable. It
maps True or False values on each item in the iterable.
>>> list(map(lambda x:x%2==0,[1,2,3,4,5]))
[False, True, False, True, False]

41. max()
A no-brainer, max() returns the item, in a sequence, with the highest value of all.
>>> max(2,3,4)
4
>>> max([3,5,4])
5
>>> max('hello','Hello')
‘hello’

42. memoryview()
memoryview() shows us the memory view of an argument.
>>> a=bytes(4)
>>> memoryview(a)
<memory at 0x05F9A988>
>>> for i in memoryview(a):
print(i)

43. min()
min() returns the lowest value in a sequence.
>>> min(3,5,1)
1
>>> min(True,False)
False

44. next()
This Python Built In function returns the next element from the iterator.

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 63


ANURAG GROUP OF INSTITUTIONS

>>> myIterator=iter([1,2,3,4,5])
>>> next(myIterator)
1
>>> next(myIterator)
2
>>> next(myIterator)
3
>>> next(myIterator)
4
>>> next(myIterator)
5
Now that we’ve traversed all items, when we call next(), it raises StopIteration.
>>> next(myIterator)
Traceback (most recent call last):
File “<pyshell#392>”, line 1, in <module>
next(myIterator)
StopIteration

45. object()
Object() Python built-in functions, creates a featureless object.
>>> o=object()
>>> type(o)
<class ‘object’>
>>> dir(o)
[‘__class__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’,
‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’,
‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’,
‘__sizeof__’, ‘__str__’, ‘__subclasshook__’] Here, the function type() tells us that it’s an
object. dir() tells us the object’s attributes. But since this does not have the __dict__ attribute,
we can’t assign to arbitrary attributes.

46. oct()
oct() converts an integer to its octal representation.
>>> oct(7)
‘0o7’
>>> oct(8)
‘0o10’
>>> oct(True)
‘0o1’

47. open()
open() lets us open a file. Let’s change the current working directory to Desktop.
>>> import os
>>> os.chdir('C:\\Users\\lifei\\Desktop')
Now, we open the file ‘topics.txt’.
>>> f=open('topics.txt')
>>> f
<_io.TextIOWrapper name=’topics.txt’ mode=’r’ encoding=’cp1252′>
>>> type(f)

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 64


ANURAG GROUP OF INSTITUTIONS

<class ‘_io.TextIOWrapper’>
To read from the file, we use the read() method.
>>> print(f.read())
DBMS mappings
projection
union
rdbms vs dbms
doget dopost
how to add maps
OOT
SQL queries
Join
Pattern programs
Output
Default constructor in inheritance

48. ord()
The function ord() returns an integer that represents the Unicode point for a given Unicode
character.
>>> ord('A')
65
>>> ord('9')
57
This is complementary to chr().
>>> chr(65)
‘A’

49. pow()
pow() takes two arguments- say, x and y. It then returns the value of x to the power of y.
>>> pow(3,4)
81
>>> pow(7,0)
1
>>> pow(7,-1)
0.14285714285714285
>>> pow(7,-2)
0.02040816326530612

50. print()
We don’t think we need to explain this anymore. We’ve been seeing this function since the
beginning of this article.
>>> print("Okay, next function, please!")
Okay, next function, please!

51. property()
The function property() returns a property attribute. Alternatively, we can use the syntactic
sugar @property. We will learn this in detail in our tutorial on Python Property.

52. range()
We’ve taken a whole tutorial on this. Read up range() in Python.

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 65


ANURAG GROUP OF INSTITUTIONS

>>> for i in range(7,2,-2):


print(i)
7
5
3

53. repr()
repr() returns a representable string of an object.
>>> repr("Hello")
“‘Hello'”
>>> repr(7)
‘7’
>>> repr(False)
‘False’

54. reversed()
This functions reverses the contents of an iterable and returns an iterator object.
>>> a=reversed([3,2,1])
>>> a
<list_reverseiterator object at 0x02E1A230>
>>> for i in a:
print(i)
1
2
3
>>> type(a)
<class ‘list_reverseiterator’>

55. round()
round() rounds off a float to the given number of digits (given by the second argument).
>>> round(3.777,2)
3.78
>>> round(3.7,3)
3.7
>>> round(3.7,-1)
0.0
>>> round(377.77,-1)
380.0
The rounding factor can be negative.

56. set()
Of course, set() returns a set of the items passed to it.
>>> set([2,2,3,1])
{1, 2, 3}
Remember, a set cannot have duplicate values, and isn’t indexed, but is ordered. Read
on Sets and Booleans for the same.

57. setattr()
Like getattr(), setattr() sets an attribute’s value for an object.
>>> orange.size

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 66


ANURAG GROUP OF INSTITUTIONS

7
>>> orange.size=8
>>> orange.size
8

58. slice()
slice() returns a slice object that represents the set of indices specified by range(start, stop,
step).
>>> slice(2,7,2)
slice(2, 7, 2)
We can use this to iterate on an iterable like a string in python.
>>> 'Python'[slice(1,5,2)]
‘yh’

59. sorted()
Like we’ve seen before, sorted() prints out a sorted version of an iterable. It does not,
however, alter the iterable.
>>> sorted('Python')
[‘P’, ‘h’, ‘n’, ‘o’, ‘t’, ‘y’]
>>> sorted([1,3,2])
[1, 2, 3]

60. staticmethod()
staticmethod() creates a static method from a function. A static method is bound to a class
rather than to an object. But it can be called on the class or on an object.
>>> class fruit:
def sayhi():
print("Hi")
>>> fruit.sayhi=staticmethod(fruit.sayhi)
>>> fruit.sayhi()
Hi
You can also use the syntactic sugar @staticmethod for this.
>>> class fruit:
@staticmethod
def sayhi():
print("Hi")
>>> fruit.sayhi()
Hi

61. str()
str() takes an argument and returns the string equivalent of it.
>>> str('Hello')
‘Hello’
>>> str(7)
‘7’
>>> str(8.7)
‘8.7’
>>> str(False)
‘False’
>>> str([1,2,3])

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 67


ANURAG GROUP OF INSTITUTIONS

‘[1, 2, 3]’

62. sum()
The function sum() takes an iterable as an argument, and returns the sum of all values.
>>> sum([3,4,5],3)
15

63. super()
super() returns a proxy object to let you refer to the parent class.
>>> class person:
def __init__(self):
print("A person")
>>> class student(person):
def __init__(self):
super().__init__()
print("A student")
>>> Avery=student()
A person
A student

64. tuple()
As we’ve seen in our tutorial on Python Tuples, the function tuple() lets us create a tuple.
>>> tuple([1,3,2])
(1, 3, 2)
>>> tuple({1:'a',2:'b'})
(1, 2)

65. type()
We have been seeing the type() function to check the type of object we’re dealing with.
>>> type({})
<class ‘dict’>
>>> type(set())
<class ‘set’>
>>> type(())
<class ‘tuple’>
>>> type((1))
<class ‘int’>
>>> type((1,))
<class ‘tuple’>

66. vars()
vars() function returns the __dict__ attribute of a class.
>>> vars(fruit)
mappingproxy({‘__module__’: ‘__main__’, ‘size’: 7, ‘shape’: ’round’, ‘__dict__’: <attribute
‘__dict__’ of ‘fruit’ objects>, ‘__weakref__’: <attribute ‘__weakref__’ of ‘fruit’ objects>,
‘__doc__’: None})

67. zip()
zip() returns us an iterator of tuples.
>>> set(zip([1,2,3],['a','b','c']))

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 68


ANURAG GROUP OF INSTITUTIONS

{(1, ‘a’), (3, ‘c’), (2, ‘b’)}


>>> set(zip([1,2],[3,4,5]))
{(1, 3), (2, 4)}
>>> a=zip([1,2,3],['a','b','c'])
To unzip this, we write the following code.
>>> x,y,z=a
>>> x
(1, ‘a’)
>>> y
(2, ‘b’)
>>> z
(3, ‘c’)

Dept. Of Information Technology Python Programming-UNIT-I - Page No. 69

You might also like