Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
52 views

UNIT - 1 Python

Python is a programming language that combines features of C and Java, allowing for both procedural and object-oriented programming. It was created by Guido van Rossum in 1991 and is an open-source, high-level language that is easy to learn, simple, portable, and has a huge standard library. Python code is compiled to bytecode that runs on the Python Virtual Machine, making programs platform independent and able to integrate with other languages. There are several flavors of Python that allow it to run on different platforms like Java, .NET, and more.

Uploaded by

Dhanush P S 107
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
52 views

UNIT - 1 Python

Python is a programming language that combines features of C and Java, allowing for both procedural and object-oriented programming. It was created by Guido van Rossum in 1991 and is an open-source, high-level language that is easy to learn, simple, portable, and has a huge standard library. Python code is compiled to bytecode that runs on the Python Virtual Machine, making programs platform independent and able to integrate with other languages. There are several flavors of Python that allow it to run on different platforms like Java, .NET, and more.

Uploaded by

Dhanush P S 107
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

UNIT – 1 Chapter -1 Introduction to Python

Python
Python is a programming language that combines the features of C and Java. It offers elegant style
of developing programs like C. If object-oriented concepts are needed Python offers classes and
objects like Java. It was developed by Guido Van Rossum in 1991 at the Centre for Mathematics and
Computer Science managed by the Dutch Government. The name Python was picked from the TV
show, Monty Python’s Flying Circus. Though the first version of python was ready in early 1990 it
was officially released for the public on 20th February 1991. It is open-source software that can be
freely downloaded by anyone from www.python.org.

Features of Python
• Simple: It is simple because when a program written in Python contains statements that
appears like English sentences. It has more clarity and less stress on understanding the syntax
of the language. Hence developing and understanding programs is easy.
• Easy to learn: Python uses very few keywords. Programs written in python use simple
structure. Hence developing a program using Python is easy. Also, it resembles C language
as most of the constructs in C are also available in Python. Hence stitching over from C to
Python is easy for programmers.
• Open source: There is no need to pay for Python software. It can be freely downloaded from
www.python.org website. The source code can be read, modified and used as desired by the
programmers.
• High level language: It uses English words to develop programs. Hence it is easy to use.
When we write programs in python, we do not need to remember the system architecture, nor
do we need to manage the memory.
• Dynamically typed: In Python we need not declare anything. An assignment statement binds
a name to an object, and the object can be of any type. If a name is assigned to an object of
one type, it may be later assigned to an object of another type. So, Python is said to as
dynamically typed language. C and Jaa are statically typed as variables and datatypes should
e mentioned properly.
• Platform independent: When compiled using a Python compiler, it generates byte code that
runs on all operating systems and hardware. Using a Python Virtual Machine (PVM), a
program can be executed on any machine. Also, Python programs are not dependent on any
specific operating system.
• Portable: When a program yields the same result on any computer in the world, it is said to
be a portable program. Python programs give the same results as they are platform
independent. A Python program can be executed on any machine that has PVM.
• Procedure and object-oriented: Python is procedure as well as object-oriented
programming language. It uses both procedures as well as classes and objects.
• Interpreted: After writing a Python program, the source code is to be compiled using a
Python compiler. Python compiler translates the Python program into an intermediate code
called byte code. This byte code is then executed on the Python Virtual Machine (PVM).
Inside the PVM, an interpreter converts the byte code into machine code so that the processor
can understand the same and produce the desired results.
• Extensible: Programs written in C or C++ can be integrated into Python and executed using
PVM.
• Embeddable: Python programs can be easily inserted into a C or C++ program. Several
applications that are already developed using Python can be integrated into other
programming languages like C, C++, Java, PHP, etc.
• Huge library: Python has a big library which can be used on any operating system.
programmers can develop programs very easily using the modules available in the Python
library.
• Scripting language: A scripting language is a programming language that does not use a
compiler for executing the source code rather it uses an interpreter to translate the source code
into machine code during execution. Python is considered as scripting language as it is
interpreted and used on the Internet.
• Database connectivity: Python provides interfaces to connect its programs to all major
databases like Oracle, MySql, Sybase.
• Scalable: Python programs are scalable since they can run on any platform and use the
features of the new platform effectively.
• Batteries included: The huge library of Python contains several applications and packages
that are already developed. They can be used by programmers to accomplish their tasks. These
packages can be used and maintained easily. Programmers need not download them
separately. These libraries are called ‘batteries included’. Some interesting packages available
in Python include
▪ agparse: A package that represents command-line parsing library
▪ botois: Amazon web services library
▪ CherryPy: An object-oriented HTTP framework
▪ Cryptography: A package that offers cryptographic techniques for the programmers
▪ Fiona: Reads and writes big data files
▪ jellyfish: A library for doing approximate and phonetic matching of strings
▪ mysql-connector-pythonis: A driver written in Python to connect MySQL database
▪ numpy: A package for processing arrays
▪ pandas: A package for powerful data structures for data analysis, time series and
statistics
▪ matplotlib: A package for drawing electronic circuits and 2D graphs
▪ Pillow: Python imaging library
▪ scipy: Scientific library to do scientific library for scientific and engineering
calculations
▪ Sphinx: Python documentation generator
▪ sympy: Package for computer algebra system (CAS) in Python
▪ w3lib: Library for web related functions
▪ whoosh: Library that contains fast and pure Python full text indexing, search and
spell-checking
In object-oriented programming the program is made up of classes. Since classes do not exist
physically, memory will not be allocated when the class is created. But objects exist physically and
hence a separate block of memory is allocated when an object is created. In Python, everything like
variables, constants, lists, functions, arrays, etc. are treated as objects.

Flavors of Python
Flavors of Python refer to different types of Python compilers. These flavors useful to integrate
various programming languages into Python.
• CPython: This is the standard Python compiler implemented in C language. In this, any
Python program is internally converted into byte code using C language functions. This byte
code is run on the interpreter available in Python Virtual Machine (PVM) created in C
language. The advantage is that it is possible to execute C and C++ functions and programs
in CPython.
• Jython: This is earlier known as JPython. This is the implementation of Python programming
language which is designed to run on Java platform. Jython compiler first compiles the Python
program into Java byte code. This byte code is executed by Java Virtual Machine (JVM) to
produce the output. Jython contains libraries which are useful for both Python and Java
programmers.
• IronPython: This is another implementation of Python language for .NET framework. This
is written in C# (C Sharp) language. The Python program when compiled gives an
intermediate language (IL) which runs on Common Language Runtime (CLR) to produce the
output. This flavor of Python gives flexibility of using both the .NET and Python libraries.
• PyPy: This is Python implementation using Python language. Actually, PyPy is written in a
language called RPython which was created in Python language. RPython is suitable for
creating language interpreters. PyPy programs run very fast since there is a JIT (Just In Time)
compiler added to the PVM. Since the original Python uses only an interpreter in the Python
Virtual Machine (PVM), the Python programs run slowly. To improve the speed of execution,
a compiler called JIT (Just In Time) is introduced into the PVM of PyPy. Hence, PyPy
programs run faster than those of Python.
• RubyPython: This is a bridge between the Ruby and Python interpreters. It encloses a Python
interpreter inside Ruby applications.
• StacklessPython: Small tasks which should run individually are called tasklets. Tasklets run
independently on CPU and can communicate with others via channels. A channel is a
manager that takes care of scheduling the tasklets, controlling them and suspending them. A
thread is a process which runs hundreds of such tasklets. Threads and tasklets can be created
in StacklessPython which is reimplementation of original Python language.
• Pythonxy: This is pronounced as Python xy and written as Python(X,Y). This is the Python
implementation that can be obtained after adding scientific and engineering related packages.
• AnacondaPython: When Python is redeveloped for handling large-scale data processing,
predictive analytics and scientific computing, it is called Anaconda Python. This
implementation mainly focuses on large scale of data.

Python Virtual Machine (PVM)


Computers understand only machine code that comprises 1s and 0s. Since computer understands only
machine code, it is imperative that any program is to be converted into machine code before it is
submitted to the computer for execution. For this purpose, compiler is necessary. A compiler
normally converts the program source code into machine code.
A Python compiler does the same task but in a slightly different manner. It converts the program
source code into another code, called byte code. Each Python program statement is converted into a
group of byte code instructions. Byte code represents the fixed set of instructions created by Python
developers representing all types of operations. The size of each byte code instruction is 1 byte (or 8
bits) and hence these are called byte code instructions. Python organization says that there may be
newer instructions added to the existing byte code instructions from time to time. The byte code
instructions are found in the .pyc file. Figure-1 shows the role of virtual machine in converting byte
code instructions into machine code

Fig. 1 The Python Virtual Machine


The role of PVM is to convert the byte code instructions into machine code so that the computer can
execute those machine code instructions and display the final output. To carry out this conversion,
PVM is equipped with an interpreter. The interpreter converts the byte code into machine code and
sends that machine code to the computer processor for execution. Since interpreter is playing the
main role, often the Python Virtual Machine is also called an interpreter.

Memory Management in Python


In C or C++, the programmer should allocate and deallocate (or free) memory dynamically, during
runtime. For example, to allocate memory, the programmer may use malloc () function and to
deallocate the memory, he may use the free () function. But in Python, memory allocation and
deallocation are done during runtime automatically. The programmer need not allocate memory
while creating objects or deallocate memory when deleting the objects. Python's PVM will take care
of such issues.
Everything is considered as an object in Python. For example, strings, lists, functions and even
modules are also objects. For every object, memory should be allocated. Memory manager inside the
PVM allocates memory required for objects created in a Python program. All these objects are stored
on a separate memory called heap. Heap is the memory which is allocated during runtime. The size
of the heap memory depends on the Random-Access Memory (RAM) of the computer and it can
increase or decrease its size depending on the requirement of the program. Figure 2 shows the
allocation of memory by PVM.

Fig. 2 Allocation of Memory by Python’s Virtual Machine


The actual memory (RAM) for any program is allocated by the underlying Operating system. On the
top of the Operating system, a raw memory allocator oversees whether enough memory is available
to it for storing objects. On the top of the raw memory allocator, there are several object-specific
allocators operate on the same heap. These memory allocators will implement different types of
memory management policies depending on the type of the objects. For example, an integer number
should be stored in memory in one way and a string should be stored in a different way. Similarly,
when we deal with tuples and dictionaries, they should be stored differently. These issues are taken
care of by object-specific memory allocators.

Garbage Collection in Python


A module represents Python code that performs a specific task. Garbage collector is a module in
Python that is useful to delete objects from memory which are not used in the program.
The module that represents the garbage collector is named as gc. Garbage collector in the simplest
way to maintain a count for each object regarding how many times that object is referenced (or used).
When an object is referenced twice, its reference count will be 2. When an object has some count, it
is being used in the program and hence garbage collector will not remove it from memory. When an
object is found with a reference count 0, garbage collector will understand that the object is not used
by the program and hence it can be deleted from memory. Hence, the memory allocated for that
object is deallocated or freed.
Garbage collector runs automatically. Python schedules garbage collector depending upon a number
called threshold. This number represents the frequency of how many times the garbage collector
removed objects. When the number of allocations – number of deallocations is greater than the
threshold number, the garbage collector will run automatically. When more and more objects are
created and if the system runs out of memory, then the automatic garbage collector will not run.
Instead, the Python program will throw an exception. The collect() method is used to perform garbage
collection manually. Manual garbage collection can be done based on time and event. However
running garbage collector too frequently will slow down the program execution.
Comparison between C and Python
Table 1 lists the differences between C and Python
Table-1 Differences between C and Python
C Python
C is procedure-oriented programming language. Python is object-oriented oriented language. It
It does not contain the features like classes, contains features like classes, objects,
objects, inheritance, polymorphism, etc. inheritance, polymorphism, etc.
C programs execute faster Python programs are slower when compared to
C. The PyPy flavor runs a bit faster but still
slower than C.
It is compulsory to declare the datatypes of Type declaration is not required in Python.
variables, arrays etc. in C.
C language type discipline is static and weak. Python type discipline is dynamic and strong.
Pointers concept is available in C. Python does not use pointers.
C does not have exception handling facility and Python handles exceptions and hence Python
hence C programs are weak. programs are robust.
C has do... while, while and for loops. Python has while and for loops.
C has switch statement. Python does not have switch statement.
The variable in for loop does not increment The variable in the for loop increments
automatically. automatically.
The programmer should allocate and deallocate Memory allocation and deallocation is done
memory using malloc(), calloc(), realloc() or automatically by PVM.
free() functions.
C does not contain a garbage collector. Automatic garbage collector is available in
Python.
C supports single and multi-dimensional arrays. Python supports only single dimensional arrays.
To work with multi-dimensional arrays, we
should use third party applications like numpy.
The array index should be positive integer. Array index can be positive or negative integer
number. Negative index represents locations
from the end of the array.
Checking the location outside the allocation of Python performs checking outside an array for
an array is not supported in C. all iterations while looping.
Indentation of statements is not necessary in C. Indentation is required to represent a block of
statements.
A semicolon is used to terminate the statements New line indicates end of the statements and
in C and comma is used to separate expressions. semicolon is used as an expression separator.
C supports in-line assignments. Python does not support in-line assignments.

Comparison between Java and Python


Table 2 lists the differences between Java and Python
Table-2 Differences between Java and Python
Java Python
Java is object-oriented programming language. Python blends the functional programming
Functional programming features are with object-oriented programming features.
introduced into Java 8.0 through lambda Lambdas are already available in Python.
expressions.
Java programs are verbose. It means they Python programs are concise and compact. A
contain more number of lines. big program can be written using very less
number of lines.
It is compulsory to declare the datatypes of Type declaration is not required in Python.
variables, arrays etc. in Java.
Java language type discipline is static and weak. Python type discipline is dynamic and strong.
In Java, the collection objects like Stack, Python collection objects like lists and
LinkedList or Vector store only objects but not dictionaries can store objects of any type,
primitive datatypes like integer numbers. including numbers and lists
Java has do... while, while, for and for each Python has while and for loops.
loops.
Java has switch statement. Python does not have switch statement.
The variable in for loop does not increment The variable in the for loop increments
automatically. But in for each loop, it will automatically.
increment automatically.
Memory allocation and deallocation is done Memory allocation and deallocation is done
automatically by JVM (Java Virtual Machine). automatically by PVM (Python Virtual
Machine).
A semicolon is used to terminate the statements New line indicates end of the statements and
and comma is used to separate expressions. semicolon is used as an expression separator.
Indentation of statements is not necessary in Indentation is required to represent a block of
Java. statements.
Java supports single and multi-dimensional Python supports only single dimensional arrays.
arrays. To work with multi-dimensional arrays, we
should use third party applications like numpy.
The array index should be a positive integer. Array index can be positive or negative integer
number. Negative index represents locations
from the end of the array.
Checking the location outside the allocation of Python performs checking outside an array for
an array is not supported in Java. all iterations while looping.

Installing Python for Windows


• https://www.python.org is the official website for python.
• Download python from Based on operating system in use.
• Steps to install Python:
▪ Double click the 'python-3.8.2.exe' file.
▪ Select the Install launcher for all users and Add Python 3.8.2 to PATH checkboxes.
▪ Click the 'Install Now' link.
▪ When Python installation is complete, ‘Setup was successful' message will be
displayed.
▪ Click the 'Close' button.

Verifying the Path

▪ During the installation process of Python, the path is automatically set to Python.
▪ We can verify the path to the Python directory in the Operating system's environment
variables.
▪ Steps to view the path to the Python directory:
▪ Right click the 'This PC' icon in Windows 10.
▪ Then click the 'Properties' option
▪ It will display a page where we should click the 'Advanced system settings' option.
▪ It will display a System Properties dialog box.
▪ Click the 'Environment Variables' button
▪ Select Advanced Tab and Click on Environment Variables Button
▪ Click the 'Edit' button present at the right side of the Edit Environment Variable dialog
box
▪ It will display the directories involved in the Path. One can observe that the directory
by the name Python38\Scripts is added to the Path
UNIT – 1 Chapter -2 Datatypes and Operators in Python
Comments in Python
There are two types of comments in Python—single line comments and multiline comments.
Single Line Comments: Single line comments in Python begin with a hash mark (#) and are useful
to mention that the entire line till the end should be treated as comment.
Example:
# Program to find the sum of two numbers
a=10 # This statement stores 10 in variable a
Here the first statement starts with # and hence the entire line will be treated as a comment and the
second line contains a statement that stores value 10 in variable a. The part of this line starting with
# symbol is a comment.
Multiline Comments: When several lines need to be marked as comments, the block of code is to
be written inside """ (triple double quotes) or ''' (triple single quotes).
Example
"""
This program is to find the net salary of an employees
by considering basic salary, house rent allowance,
dearness allowance, provident fund and income tax
"""
Or

'''
This program is to find the net salary of an employees
by considering basic salary, house rent allowance,
dearness allowance, provident fund and income tax
'''
Docstrings
Using """ or ''' for comments in Python are not recommended as they occupy memory and would
waste time of the interpreter since the interpreter has to check them. Python documentation string or
commonly known as docstring, is a string literal, and it is used in the class, module, function, or
method definition. An object's docstring is defined by including a string constant as the first statement
in the object's definition.
Docstrings are great for 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. The docstring is written simply like multiline comments using
multiline strings but it must be the first statement in the object’s definition.
Example-1:
def square(n):
'''Takes a number n, and returns the square if n '''
return n**2
Datatypes in Python
A datatype represents the type of data stored into a variable or memory. The datatypes which are
already available in Python are called built-in datatypes. The datatypes which can be created b the
programmers are called user-defined datatypes.
Built-in datatypes:
1. None type
2. Numeric types
3. Sequences
4. Sets
5. Mappings
The None Type: The None datatype in Python represents an object that does not contain any value.
In Java such an object is called null object. In a Python program, maximum of only one ‘None’ object
is provided. One of the uses of None is that it is used inside a function as a default value of the
arguments. When calling a function, if no value is passes, then the default value will be taken as
‘None’. None is not the same as 0, False, or an empty string.
Example:
x = None
print(x) # will display the output None
Numeric Types: In Python, numeric data type represents the data that has a numeric value. The
numeric value can be an integer, floating number, or even complex number. These values are
defined as int, float, and complex classes in Python.
• int datatype – This data type is represented with the help of int class. It consists of positive
or negative whole numbers (without fraction or decimal). In Python, there is no limit for the
size of an int datatype. It can store very large integer numbers conveniently. Example: a=-57
• float datatype: The float datatype represents floating point numbers. A floating point number
is a number that contains a decimal point. Example nm=56.994456. Floating point numbers
can also be written in scientific notations using ‘e’ or ‘E’ as x=22.55e3. The meaning is
x=22.55× 103
• complex datatype: A complex number is a number that is written in the form a + bj or a +
bJ. Here a represents the real part and b represents the imaginary part. The suffix j or J
associated with b indicates that the square root value of -1. Example 3 + 3j, 5.5 + 8.0J.
Example Program -1:
#Python Program to add two complex numbers
c1= 2+ 3J
c2=3-2J
c3=c1+c2
print("Sum = ", c3) Output: Sum = (5+1j)

Representing Binary, Octal and Hexadecimal Numbers


A binary number should be written by prefixing 0b or 0B before the value. 0b1010101, 0B1011010
are treated as binary numbers. Hexadecimal numbers are written by prefixing 0x or 0X. 0xab123,
0X23FF9 are valid hexadecimal numbers. Octal numbers are written by prefixing 0o or 0O. 0o12345,
0O12674 are the examples of Octal numbers.

Converting the Datatypes Explicitly


Depending on the type of data, Python internally assumes the datatype of the variable. But sometimes,
the programmer may require to convert one datatype into another. This process is called type
conversion or coercion. This is done by mentioning the datatype in parentheses.
Example Program-2
x=123.56
print (int(x)) # will display 123
x=123
print (float(x)) # will display 123.0
x=12
print (complex(x)) # will display (12+0j)

Example Program-3:
#Program to convert into decimal number system
n1=0O17
n2=0B1110010
n3=0X1C2 Output:
n=int(n1) Octal 017 = 15 in decimal
print(' Octal 017 = ', n , 'in decimal') Binary 0B1110010 = 114 in decimal
n=int(n2) Hexadecimal 0X1C2 = 450 in decimal
print(' Binary 0B1110010 = ', n , 'in decimal')
n=int(n3)
print(' Hexadecimal 0X1C2 = ', n , 'in decimal')
There is a function in the form int(string, base) that is used to convert a string into a decimal integer.
‘string’ represents the string format of the number. It should contain an integer in string format. ‘base’
represents the base of the number system to be used for string. For example, base 2 indicates it is
binary.
Example Program-4
#Program to convert into decimal number system
s1="0O17"
s2="0B1110010" Output:
s3="0X1C2" Octal 017 = 15 in decimal
n=int(s1, 8)
Binary 0B1110010 = 114 in decimal
print(' Octal 017 = ', n , 'in decimal')
Hexadecimal 0X1C2 = 450 in decimal
n=int(s2, 2)
print(' Binary 0B1110010 = ', n , 'in decimal')
n=int(s3, 16)
print(' Hexadecimal 0X1C2 = ', n , 'in decimal')
It is possible to use bin() to convert given number into binary number system. The oct() function will
convert a number into octal and hex() will convert a number into hexadecimal.
Example Program-5
#Program to demonstrate bin(), oct() and hex()
A=10
Output:
print('Decimal ', a)
print('Binary ', bin(a)) Decimal 10
print('Octal ', oct(a)) Binary 0b1010
print('Hexadecimal ', hex(a)) Octal 0o12
Hexadecimal 0xa
bool Datatype
This datatype represents Boolean values True and False. Python Internally represents True as 1 and
False as 0. A blank string like “” is also represented as False. Condition will be evaluated internally
to either True or False.
Example-1: Example-2
a=10 a=10>5 #a is treated as bool type
b=20 print(a) #displays True
if(a<b): print “Hello” #Displays Hello a=5>10
print(a) #displays False
Sequences in Python
A sequence represents a group of items. There are six types of sequences in Python. They are: str,
bytes, bytearray, list, tuple and range.
str Datatype
In Python str represents string datatype. A string is represented by a group of characters. Strings are
enclosed using single quotes or double quotes. Strings can also be represented using triple quotes.
Triple and double quotes are useful to embed a string in another.
Examples:
str1= “Hello world”
str2= ‘Hello world’
str3= “”” Python is a ‘High level’ Programming Language”””
The slice operator represents square brackets [ and ] to retrieve pieces of a string. Characters in a
string are counted from 0 onwards.
Example Program-5
#Demonstration of string operations Output:
s='Welcome to Core Python' Welcome to Core Python
print(s) W
print(s[0]) #Prints first character come
print (s[3:7]) #Prints 4th to 7th character Core Python
print(s[11:])# Prints from 11th character n
print(s[-1])#Prits 1st character from the end Welcome to Core PythonWelcome to Core Python
print(s*2) # Repeats the string twice
bytes Datatype
The bytes datatype represents a group of byte numbers just like an array does. A byte number is any
positive integer from 0 to 255. A byte array can store numbers from 0 to 255 and it cannot even store
negative numbers. The elements of a byte array cannot be modified.
Example:
Elements=[10, 20, 30, 40, 0, 15 ] # This is a list of byte numbers
x=bytes(elements) #Convers the list into byte array
print(x[0]) displays the first element that is 10
Example Program-6 Output:
#Program to understand byte type array 10
elements=[10, 20, 0, 40, 15] 20
x=bytes(elements) 0
for i in x : print(i) 40
15
bytearray Datatype
The bytearray datatype is similar to bytes datatype. The difference is that the bytes type array cannot
be modified but bytearray type array can be modified.
Example:
Elements=[10, 20, 30, 40, 0, 15 ] # This is a list of byte numbers
x=bytearray(elements) #Convers the list into byte array
print(x[0]) displays the first element that is 10
We can modify the elements of bytearray as follows:
x[0]=88 Output:
x[1]=11 10
20
Example Program-7 0
#Program to understand bytearray type array 40
elements=[10, 20, 0, 40, 15] 15
x=bytearray(elements) 88
for i in x : print(i) 99
x[0]=88 0
x[1]=99 40
for i in x : print(i) 15

list Datatype
Lists in Python are similar to arrays in C and Java. A list represents a group of elements. Just like an
array, a list can store elements. But there is one major difference between an array and a list. An array
can store only one type of elements whereas a list can store different types of elements. Hence lists
are more versatile and useful than an array. Lists are the most used data type in Python programs.
Indexing and slicing operations are commonly done on lists. Indexing represents accessing elements
by their position numbers in the list. The position numbers start from 0 onwards and are written inside
square braces.
Example Program-8
#Demonstrate use of lists Output:
list=[10, -20, 12.5, 'Vijay', 'Mary'] [10, -20, 12.5, 'Vijay', 'Mary']
print(list) 10
print(list[0]) Vijay
print(list[3]) [-20, 12.5]
print(list[1:3]) Vijay
print(list[-2]) [10, -20, 12.5, 'Vijay', 'Mary', 10, -20, 12.5, 'Vijay', 'Mary']
print(list*2)
tuple Datatype
A tuple is similar to a list. A tuple contains a group of elements which can be of different types. A
tuple is a Python sequence which stores a group of elements or items. Tuples are similar to lists but
the main difference is tuples are immutable whereas lists are mutable. Since tuples are immutable,
once created they cannot be modified. That means tuple can be treaded as read-only list.
Tuples are generally used to store data which should not be modified and retrieve that data on
demand. We can create a tuple by writing elements separated by commas inside parentheses (). The
elements can be of same datatype or different types. For example, to create an empty tuple, we can
simply write empty parenthesis, as:
tup1 = () # creates an empty tuple
tup2 = (10, 20, -30.1, 40.5, 'Hyderabad', 'New Delhi')
The individual elements of the tuple can be referenced using square braces as tup2[0], tup2[3] and so
on. If an element of the tuple is modified as
tup2[0]=99 will generate an error as tuple are immutable.
Example Program-9 Output:
#Demonstrate use of tuple [10, -20, 12.5, 'Vijay', 'Mary']
tuple =[10, -20, 12.5, 'Vijay', 'Mary'] 10
print(tuple) Vijay
print(tuple[0]) [-20, 12.5]
print(tuple[1:3]) Vijay
print(tuple[-2]) [10, -20, 12.5, 'Vijay', 'Mary', 10, -20, 12.5, 'Vijay', 'Mary']
print(tuple*2)
range Datatype
The range datatype represents a sequence of numbers. The numbers in the range are not modifiable.
In case the start index is not given, the index is considered as 0, and it will increment the value by 1
till the stop index. For example range(5) will output you values 0,1,2,3,4 . The range()is a very
useful command and mostly used when you have to iterate using for loop.
Example Program-10
#Demonstrate use of range
r=range(10)
for i in r : print(i)# will display 0 to 10 as output
Starting number, ending number and range can be specified in case of a range. For example:
r=range(30, 40, 2)
This will create a range as 30, 32, 34, 36, 38, 40.
A list can be created by specifying a range as follows:
Example Program-11
#Demonstrate use of range Output:
lst=list(range(20, 40, 2)) [20, 22, 24, 26, 28, 30, 32, 34, 36, 38]
print(lst)
Sets
A set is an unordered collection of elements much like a set of mathematics the order of elements is
not maintained in the sets. It means the elements may not appear in the same order as they are entered
into the set. A set does not accept duplicate elements. There are two sub types namely set datatype
and frozenset datatype.
set Datatype
To create a set, the elements are to be entered within curly braces. They must be separated by
commas.
Example Program-12
#Demonstrate use of sets
s={10, 20, 50, 20, 40}
print(s)
The above program may print 40, 10, 50, 20. In the above example the element 20 is repeated but it
is stored only once in a set. Since sets are unordered it is not possible to retrieve the individual
elements using indexing or slicing.
Example:
s={10, 20, 50, 20, 40}
print(s[0])
print (s[1:3]) will generate errors.
The update() method is used to add elements to a set and the remove() method is used to remove a
particular element from the list.
Example Program-12
#Demonstrate use of update and remove Output:
s={1,2, 3, 4, 5} {1, 2, 3, 4, 5, 50, 60}
s.update({50, 60}) {1, 2, 3, 4, 5, 50}
print (s)
s.remove(60)
print(s)
frozenSet Datatype
The frozenset datatype is same as the set datatype. The main difference is that the elements in the set
datatype can be modified; whereas the elements of the frozenset cannot be modified.
Example
fs=frozenset({1,2, 3, 4, 5})
print (fs)
The methods update() and remove() will not work on frozensets as they cannot be modified.
Mapping Types
A map represents a group of elements in the form of key value pairs so that when the key is given,
the value associated with it can be retrieved. The ‘dict’ datatype is an example of a map. The ‘dict’
represents a directory that contains pair of elements key and a value. The key and value should be
seperated by a colon (:) and every pair should be separated by a comma. All elements should be
enclosed in curly braces. A dictionary can be created by typing roll numbers and names of students.
Here roll number is the key and name is the value. Various operations can be performed on
dictionaries. To retrieve the value upon a given key it is enough to enter d[key]. To retrieve only key
from the dictionary, the keys() method can be used. To get only values the values() method can be
used.
Example Program-13
#Demonstarate creation of mapping
d={101:'Ajay', 102:'Anup', 103: 'Bindu', 104:'Deepa'}
print(d) Output:
print(d[102]) {101: 'Ajay', 102: 'Anup', 103: 'Bindu', 104: 'Deepa'}
print(d.keys()) Anup
print(d.values()) dict_keys([101, 102, 103, 104])
d[104]='Deepak' dict_values(['Ajay', 'Anup', 'Bindu', 'Deepa'])
print(d) {101: 'Ajay', 102: 'Anup', 103: 'Bindu', 104: 'Deepak'}
Literals in Python
Literal is a constant value that is stored into a variable in a program.
Example: a=123
Here ‘a’ is the variable into which the constant value 123 is stored. Hence the value 123 is called
literal. Since 123 indicates integer value, it is called ‘integer literal’. Different types of literals in
Python include: Numeri literals, Boolean literals, and String literals
• Numeric literals: These literals represent numbers. Different types of numeric literals
available in Python are represented in Table-3.
Table-3 Numeric Literals in Python
Examples Liter Name
450, 123, 15, -10, -99 Integer Literal
3.12286, 10.6, -10.8, 9.8E3 Float Literal
0x5A1c, 0X12abc Hexadecimal Literal
0O556633, 0o12345 Octal Literal
0b1100101, 0B1110110101 Binary Literal
19+3J, 16-2j, 2-9J Complex Literal
• Boolean literal: Boolean literals are the True or False values stored into a bool type
variable.
• String literals: A group of characters is called string. String literals are enclosed in single
quotes (‘), double quotes (“) or triple quotes (‘’’ or “””). In Python there is no difference
between single quoted and double quoted strings. Single quoted and double quoted strings
should end in the same line. When a string literal extends beyond a single line, they should
be represented using triple quotes.
Examples
s1=’This is first Indian Book’
s2= “Core Python for Beginners”
s3=’’’ This is the first Indian Book on Core Python that explores
All the useful features of Python ‘’’
s4=””” This is the first Indian Book on Core Python that explores
All the useful features of Python”””
Escape characters in Python
To insert characters that are illegal in a string, one can use an escape character. An escape character
is a backslash \ followed by the character to be inserted. Table-4 lists some escape characters in
Python.
Table-4 Escape Characters in Strings
Escape Character Meaning
\ New line continuation
\\ Display single \
\’ Display a single quote
\” Display a double quote
\b Backspace
\r Enter
\t Horizontal tab space
\v Vertical tab
\n New line
Determining the Datatype of a Variable
The type() function can be used to know the datatype of an object.
Example
a=123
print(type(a)) # will display <class ‘int’>
since a is an object of class int in Python the above Python statement displays <class ‘int’ > as output.
Characters in Python
The programming languages such as C and Java contain char datatype that represents a single
character. Python does not have a char datatype to represent individual characters. It uses the str type
which represents strings.
User-defined Datatypes
The datatypes which are represented by the programmer are called ‘user-defined’ datatypes. Arrays,
classes, modules, etc. are user-defined datatypes in Python.
Constants in Python
A constant is similar to a variable but its value cannot be modified or changed in the course of a
program execution. Once defined, a constant cannot allow changing its value. In C and Java defining
a constant is possible but in Python that is not possible. A programmer can indicate a variable as
constant by writing its name in all capitals. For example, MAX_DATA but its value can be changed.
Identifiers and Reserved words
An identifier is a name that is given to a variable or a function or a class, etc. Rules for defining an
identifier in Python:
1. An identifier must start with a letter or the underscore character.
2. An identifier cannot start with a number.
3. An identifier can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
4. Identifiers are case-sensitive (age, Age and AGE are three different variables).
5. A reserved word cannot be used as identifier
Examples: Basic_Salary, Roll_Number, a, name11, income_tax
Reserved words (also called keywords) are defined with predefined meaning and syntax in the
language. These keywords have to be used to develop programming instructions. Reserved words
can’t be used as identifiers for other programming elements like name of variable, function etc. Table-
5 lists different reserved words in Python.
Table-5 Reserved Words in Python
and as assert break class continue def del
elif else except exec finally for from global
if import in is lambda nonlocal not or
pass print raise return try while with yield
False True
Naming Conventions in Python
Python developers made some suggestions to the programmers regarding how to write names of
functions, variables, packages, classes, etc. These rules are called naming conventions. Following
are the naming conventions to be followed:
• Package: Package names should be written in all lowercase letters. When multiple words are
used for a name, they need to be separated using underscore ( _ )
• Modules: Modules names should be written in all lowercase letters. When multiple words are
used for a name, they need to be separated using underscore ( _ )
• Classes: Each word of a class name should start with a capital letter. Python’s built-in class names
use all lowercase characters. When class represents exception, then its name should end with the
word ‘Error’
• Global variables or Module-level variables: Global variables names should ne all lowercase
letters. When multiple words are used, they should be separated using underscore ( _ )
• Instance variables: Instance variables names should be all lower case letters. When multiple
words are used for a name, they need to be separated using underscore ( _ ). Non-public instance
variables should begin with an underscore.
• Functions: Function names should be all lower case letters. When multiple words are used for a
name, they need to be separated using underscore ( _ ).
• Methods: Method names should be all lower case letters. When multiple words are used for a
name, they need to be separated using underscore ( _ ).
• Method arguments: In case of instance methods, their first argument name should be ‘self’. In
case of class methods, their first argument name should be ‘cls’
• Constants: Constants names should be written in all capital letters. When multiple words are
used for a name, they need to be separated using underscore ( _ ).
• Non accessible entities: Some variables, functions and methods are not accessible outside and
they should be used as they are in the program. such entities names are written with two double
quotes before and two double quotes after.
UNIT – 1 Chapter -4 Input and Output
To provide input to a computer, Python provides some statements which are called as Input
statements. Similarly, to display the output, there are Output statements available in Python.
Output statements
To display output or results, Python provides print() function. When print() is called without any
argument then Python sends the cursor to the next line
Some Examples
print(‘Hello’)
print(“Hello”)
print (“This is the first line \n and this is the second”)
print(‘Hello \t World’)
print(3 * “Hai”)
The ‘+’ operator when used on numbers will perform addition operation. The same + when used on
strings strings performs concatenation. When two strings are concatenated using + operator, they are
joined without any space in between. If a space is required between strings when printing, a comma
can be used.
Examples:
print('City name ='+ 'Bengaluru')
print('City name =', 'Chennai’) # Two strings are separated by space
Values of variables can be printed using print() function
a,b=2,4 Output:
print(a) 2
print(a,b)
24
print(a,b, sep=",") # uses , as separator
24
print(a,b, sep=":")# uses : as separator
2:4
Each print() will display the output in a separate line as each print() function throws the cursor to the
next line after displaying the output. It is possible to specify the end character by making use of the
‘end’ attribute. If end= ‘’ is used then the ending character of the line will be nothing. Also backslash
character such as ‘\t’ can be used as an ending character.
Examples
print(“Hello”, end=" "
print(“Dear”, end=" ")
print(“Students”) # will display Hello Dear Students in the same line.
Objects such as tuples, lists, dictionaries can be passed to print() function to display the elements.
Examples
lst=[10, 20, 'A', 12.5] Output:
print(lst) [10, 20, 'A', 12.5]
dict={'Idly':30.00, 'Roti':45.00, 'Dosa': 50.00} {'Idly': 30.0, 'Roti': 45.0, 'Dosa': 50.0}
print(dict) dict_keys(['Idly', 'Roti', 'Dosa'])
print(dict.keys()) dict_values([30.0, 45.0, 50.0])
print(dict.values())
The print(formatted string) Statement
The output displayed in the print() function can be formatted according to user’s choice. The special
character % is used to format the output.
• Syntax: print(“formatted string” %(variables list))
In formatted string %i or %d can be used to represent decimal integer numbers, %f for floating point
numbers, %s for strings. If there is only one variable it can be written without parenthesis
Examples
x=10
print('Value =%i' % x)
x,y=100, 150
print('x =%i y =%d' % (x, y))
Printing Formatted Strings
To display formatted strings %s is to be used. If %20s is used, Python will allot 20 spaces and the
string is right aligned in those spaces. To align the string towards the left %-20s is to be used.
Examples Output:
Name='Bindu' Hai Bindu
print('Hai %s' %Name) Hai Bindu
print('Hai %20s' %Name) Hai ( Bindu)
print('Hai (%20s)' %Name) Hai (Bindu )
print('Hai (%-20s)' %Name) Hai B i
print('Hai %c %c' %(Name[0], Name[1])) Hai Bin
print('Hai %s' %(Name[0:3]))
When %.3f is used, the float value is displayed with 3 fraction digits after the decimal point. The
digits before decimal point will be displayed as they are
Examples
num=123.456789 Output:
print('Number =', num)
Number = 123.456789
print('Formatted number %.3f' %num)
Formatted number 123.457
print('The value %8.2f' %num)
The value 123.46 (Observe 2 spaces after value)
Inside formatted string, replacement field can be used by using {}. The names of indexes can be
mentioned in these replacement fields. The names of Output:
indexes represent the order of values. number-1=1
Example number-1=1 number-2=10 number-3=5
n1, n2, n3= 1, 10, 5
print('number-1={0}'.format(n1))
print('number-1={0} number-2={1} number-3={2}'.format(n1, n2, n3))
Input Statements
Python provides input() function to accept input from the user. This function takes a value from the
keyboard and returns it as a string. It is always better to display a message to the user so that the
user can understand what to enter.
Example
str=input("Enter your name ")
print("Hello", str)
If the inputs need to be converted to a datatype other than string then the corresponding conversion
function is to be used. For example int() for integers float() for floating point datatype and so on.
Python accepts a character as string. If only one character is needed then indexing is to be used
Example:
ch=input('Enter a character ') Output:
print('You entered', ch[0]) Enter a character Asdf
Accepting Integers You entered A
Method-1
#Accepting integers
x=int(input('Enter first number '))
y=int(input('Enter second number ‘))
y=int(input('Enter second number '))
print('X=', x, ‘Y=’, y, ‘Z=’,z)
Method-2
#Accepting three numbers
a, b, c=[int(x) for x in input("Enter three numbers ").split()]
print(a, b, c)
To accept more than one input in the same line a for loop can be used along with the input statement
as mentioned in the above statement. The split() method by default splits the values where a space is
found. Hence, when entering numbers, the user should separate them using a blank space. The
square brackets [] indicate that the input accepted will be in the form of elements of a list.
lst=[x for x in input('Enter strings : ').split(',')] #accepts strings separated by comma
print('Your List', lst)
a,b,c=[int(x) for x in input('Enter three numbers ').split(',')]
sum=a+b+c
print('Sum=',sum)
The eval() function
The eval() function takes a string and evaluates the result of the string by taking it as a Python
expression. Example “a+b-5” where a=10, b=15 will be evaluated as 20. If a string expression is
passed to eval() the result of the expression passed will be returned
Example
#Use of eval() function
a, b= 5, 10
result=eval("a+b-5")
print("Result=", result)# will display 10 as Result

Command Line Arguments


It is possible to pass inputs to the program at the time of execution of the program. The arguments
that are passed during execution time are called command line arguments. To do this Python
program is to be executed using Command Prompt as follows:
C:\Python Add.py 10 25
There Add.py is the name of the program, 10 and 25 are the arguments that are passed during
execution. These arguments are stored by default as strings with the name argv which is available in
the sys module. argv[0] represents the name of the program, argv[1] represents the first value and
argv[2] represents the second value. The len() function is used to find the number of arguments
entered at the command prompt
Example
# Program to display Command Line Arguments
import sys
n=len(sys.argv) #Stores total number of arguments in n
args=sys.argv
print("No. of arguments passed ", n)
print("Argument are ", args)
print("Arguments one by one")
for a in args
print (a)

#To add two numbers.


#Save this program as add.py
import sys
#Convert arguments into integer Output:
sum=int(sys.argv[1])+int(sys.argv[2]) C:>Python add.py 10 22
print("Sum=",sum)
Sum= 32

#To sum of even numbers only


import sys
#Read all arguments except program name
args=sys.argv[1:]
print(args) Output:
sum=0 C:>Python Sum.py 10 22 6 9 11 1 12
for a in args Sum of only even numbers 50
x=int(a)
if x%2==0:
sum=sum+x
print("Sum of only even numbers ", sum
UNIT – 1 Chapter -3 Operators in Python
An operator is a symbol that performs an operation. An operator acts on some variables, called
operands to get the desired result. In a statement if we write a + b, a, b are variables or operands and
+ is the operator. If an operator acts on a single variable, it is called unary operator; if it acts on two
variables, it is called binary operator; and if it acts on three variables, then it is called ternary operator.
Operators can also be classified based on their nature as follows
• Arithmetic operators • Boolean operators
• Assignment operators • Bitwise operators
• Unary minus operator • Membership operators
• Relational operators • Identity operators
• Logical operators
Arithmetic Operators
These operators are used to perform basic arithmetic operations like addition, subtraction, division,
etc. There are seven arithmetic operators available in Python. Since these operators act on two
operands, they are called 'binary operators' also. Assume a = 7 and b = 3 and the effect of various
arithmetic operators is listed in Table-6
Table 6 Arithmetic Operators in Python
Operator Meaning Example Result
+ Addition operator. Adds two values. a+b 10
- Subtraction operator. Subtracts one value from a-b 4
another.
* Multiplication Operator. Multiplies values on a*b 21
either side of the operator.
/ Division Operator. Divides left operand by the a/b 2.3333333333333335
right operand.
* Modulus Operator. Gives remainder of division. a%b 1
** Exponent Operator. Calculates exponential a**b 343
power value. a**b gives the value of a to the
power of b.
// Integer Division. This is also called as Floor a//b 2
Division and gives only integer quotient.
When there is an expression that contains several arithmetic operators, we should know which
operation is done first and which operation is done next. In such cases, the following order of
evaluation is used:
1. First parentheses are evaluated.
2. Exponentiation is done next.
3. Multiplication, division, modulus and floor divisions are at equal priority.
4. Addition and subtraction are done afterwards.
5. Finally, assignment operation is performed.
Let the expression be : d = (x+y)*z**a//b+c.
Assume the values of variables as: x=1; y=2; z=3; a=2; b=2; c=3.
Then, the given expression d = (1+2)*3**2//2+3 will evaluate as:
1. First parentheses are evaluated. d = 3*3**2//2+3.
2. Exponentiation is done next. d = 3*9//2+3.
3. Multiplication, division, modulus and floor divisions are at equal priority. d = 27//2+3 and
then d = 13+3.
4. Addition and subtraction are done afterwards. d = 16.
5. Finally, assignment is performed. The value 16 is now stored into 'd'. Hence, the total value
of the expression becomes 16 which is stored in the variable 'd'. For order of precedence,
just remember this PEMDAS (similar to BODMAS)

Using Python Interpreter as Calculator


The Python interpreter can be used as a simple calculator that can perform basic arithmetic
operations. To do this the user needs to open Python IDLE and type arithmetic operations to be
performed.
Example
>>> 13+5
18
>>> 13-5
8
Assignment Operators
These operators are useful to store the right-side value into a left side variable. These operators are
shown in Table-7. Assume the values x = 20, y = 10 and z = 5:
Table-7 Assignment Operators in Python
Operator Example Meaning Result
= z=x+y Assignment operator. Stores right side value into left side z =30
variable, i.e. x+y is stored into z.
+= z+=x Addition assignment operator. Adds right operand to the left z =25
operand and stores the result into left operand, i.e. z = z+x.
-= z-=x Subtraction assignment operator. Subtracts right operand z =15
from left operand and stores the result into left operand, i.e.
z = z-x.
*= z*=x Multiplication assignment operator. Multiplies right operand z =100
with left operand and stores the result into left operand, i.e. z
= z *x.
/= z/=x Division assignment operator. Divides left operand with right z =0.25
operand and stores the result into left operand, i.e. z = z/x.
%= z%=x Modulus assignment operator. Divides left operand with z=5
right operand and stores the remainder into left operand, i.e.
z = z%x.
**= z**=x Exponentiation assignment operator. Performs power value z= 9765625
and then stores the result into left operand, i.e. z = z**y.
//= z//=x Floor division assignment operator. Performs floor division z=0
and then stores the result into left operand, i.e. z = z// y.
It is possible to assign the same value to two variables in the same statement as:
a=b=1
print(a, b) #will display 1 1
Another example is where we can assign different values to two variables as:
a=1; b=2
print(a, b) #will display 1 2
The same can be done using the following statement:
a, b = 1, 2
print(a, b) #will display 1 2
A word of caution: Python does not have increment operator (++) and decrement operator (--) that
are available in C and Java.
Unary Minus Operator
The unary minus operator is denoted by the symbol minus (-). When this operator is used before a
variable, its value is negated. That means if the variable value is positive, it will be converted into
negative and vice versa.
Example:
n = 10
print(-n) #displays -10
num = -10
num = - num
print(num) #displays 10
Relational Operators
Relational operators are used to compare two quantities. We can understand whether two values are
same or which one is bigger or which one is lesser, etc. using these operators. These operators will
result in True or False depending on the values compared, as shown in Table -8. In this table, assume
that a =1 and b = 2.
Table-8 Relational Operators in Python
Operator Example Meaning Result
> a>b Greater than operator. If the value of left operand is greater than False
the value of right operand, it gives True else it gives False.
>= a>=b Greater than or equal operator. If the value of left operand is False
greater or equal than that of right operand, it gives True else False.
Greater than or equal operator. If the value of left operand is
greater or equal than that of right operand, it gives True else False.
< a<b Less than operator. If the value of left operand is less than the value True
of right operand, it gives True else it gives False.
<= a<=b Less than or equal operator. If the value of left operand is lesser or True
equal than that of right operand, it gives True else False.
== a==b Equals operator. If the value of left operand is equal to the value False
of right operand, it gives True else False.
!= a!=b Not equals operator. If the value of the left operand is not equal to True
the value of right operand, it returns True else it returns False.
Relational operators are generally used to construct conditions in if statements.
Example:
a=1; b=2
if (a>b):
print("Yes")
else:
print("No")
Relational operators can be chained. It means, a single expression can hold more than one relational
operator. For example,
x=15 Output:
10<x<20 #displays True No
Here, 10 is less than 15 is True, and then 15 is
less than 20 is True. Since both the conditions are evaluated to True, the result will be True.
x=15
10>=x<20 #displays False
Here, 10 is greater than or equal to15 is False, and then 15 is less than 20 is True.
10<x>20 #displays False
1<2<3<4 #displays True
1<2>3<4 #displays False
4>2>=2>1 #displays True
Logical Operators
Logical operators are useful to construct compound conditions. A compound condition is a
combination of more than one simple condition. Each of the simple condition is evaluated to True or
False and then the decision is taken to know whether the total condition is True or False. We should
keep in mind that in case of logical operators, False indicates 0 and True indicates any other number.
There are 3 logical operators as shown in Table-9. Assume x = 1 and y=2 in this table.
Table-9 Logical Operators in Python
Operator Example Meaning Result
and x and y and operator. If x is False, it returns x, otherwise it returns y. 2
or x or y or operator. If x is False, it returns y, otherwise it returns x. 1
not not x not operator. If x is False, it returns True, otherwise False. False
Examples
a= True b= False
a and a #displays True
b and b #displaysFalse
a and b #displaysFalse
a or a #displays True
a or b #displays True
b or b #displays False
not a #displays False
not b #displays True
Bitwise Operators
These operators act on individual bits (0 and 1) of the operands. We can use bitwise operators
directly on binary numbers or on integers also. When we use these operators on integers, these
numbers are converted into bits (binary number system) and then bitwise operators act upon those
bits. The results given by these operators are always in the form of integers. There are 6 types of
bitwise operators as shown below:
• Bitwise Complement operator (~)
• Bitwise AND operator (&)
• Bitwise OR operator (|)
• Bitwise XOR operator (^)
• Bitwise Left shift operator (<<)
• Bitwise Right shift operator (>>)
Bitwise Complement Operator (~)
This operator gives the complement form of a given number. This operator symbol is ~, which is
pronounced as tilde. Complement form of a positive number can be obtained by changing 0's as 1's
and vice versa. Shortcut for finding the complement of a given number is ~x = -(x+1)
~ 25 = - ( 25 + 1) = -26
~ -31 = - ( -31 + 1) = 30
Bitwise AND Operator (&)
This operator performs AND operation on the individual bits of numbers. The symbol for this
operator is &, which is called ampersand. This operation gives 1 as output when both the
corresponding bits are 1 otherwise it will give output 0.
X = 10 = 0000 1010
Y = 11 = 0000 1011
X & Y = 0000 1010 (x & y = 10)
Bitwise OR Operator (|)
This operator performs OR operation on the bits of the numbers. The symbol of bitwise OR operator
is |, which is called pipe symbol. This operation gives output 0 when both the corresponding bits
are 0s, otherwise it will give output 1.
X = 10 = 0000 1010
Y = 11 = 0000 1011
X | Y = 0000 1011 (x|y=11)
Bitwise XOR Operator (^)
This operator performs exclusive or (XOR) operation on the bits of numbers. The symbol is ^, which
is called cap, carat, or circumflex symbol.
X = 10 = 0000 1010
Y = 11 = 0000 1011
X ^ Y = 0000 0001 (x ^ y = 1)
Bitwise Left Shift Operator (<<)
This operator shifts the bits of the number towards left a specified number of positions. The symbol
for this operator is <<, read as double less than. If we write x<<n, the meaning is to shift the bits of
x towards left n positions.
If x = 10, calculate x value if we write x<<2.
Shifting the value of x towards left 2 positions will make the leftmost 2 bits to be lost.
The value of x is 10 = 0000 1010. Now, x<<2 will be 0010 1000 = 40 (in decimal). The procedure to
do this is explained, as shown in Figure-3

Fig. 3: Bitwise Left-shift Operation


Bitwise Right Shift Operator (>>)
This operator shifts the bits of the number towards right a specified number of positions. The symbol
for this operator is >>, read as double greater than. If we write x>>n, the meaning is to shift the bits
of x towards right n positions.
If x = 10, then calculate x>>2 value. The operation is shown in Figure 4.
Shifting the value of x towards right 2 positions will make the rightmost 2 bits to be lost. x value is
10 = 0000 1010. Now x>>2 will be: 0000 0010 = 2 (in decimal)

Fig. 4: Bitwise Right-shift Operation


Membership Operators
The membership operators are useful to test for membership in a sequence such as strings, lists, tuples
or dictionaries. For example, if an element is found in the sequence or not can be asserted using these
operators. There are two membership operators are: in and not in
The in Operator
This operator returns True if an element is found in the specified sequence. If the element is not
found in the sequence, then it returns False.
The not in Operator
This works in reverse manner for 'in' operator. This operator returns True if an element is not found in
the sequence. If the element is found, then it returns False.
Examples:
s="Welcome to Python Programming"
print("Python" in s) Output:
print("Java" in s) True
print("Java" not in s) False
print("c" not in s) True
Identity Operators False
These operators compare the memory locations of two objects. Hence, it is possible to know
whether the two objects are same or not. The memory location of an object can be seen using the id()
function.
This function returns an integer number, called the identity number that internally represents the
memory location of the object. For example, id(a) gives the identity number of the object referred by
the name 'a'.
>>> a=29
>>> b=39
>>> id(a)
1699277760
>>> id(b)
1699277920
There are two identity operators namely is and is not
The is Operator
The 'is' operator is useful to compare whether two objects are same or not. It will internally compare
the identity number of the objects. If the identity numbers of the objects are same, it will return True;
otherwise, it returns False.
Example:
>>> a=26
>>> b=26
Output:
>>> a is b
True
>>> a=26
>>> b=10 False
>>> a is b

The is not Operator


This is not operator returns True, if the identity numbers of two objects being compared are not same.
If they are same, then it will return False.
The 'is' and 'is not' operators do not compare the values of the objects. They compare the identity
numbers or memory locations of the objects. If the value of the objects needs to be compared,
the equality operator (==) is to be used.
Operator Precedence and Associativity
An expression or a formula may contain several operators. In such a case, the programmer should
know which operator is executed first and which one is next. The sequence of execution of operators
is called operator precedence. Table-10 shows operator precedence in Python. The operator having
highest precedence is listed on the top of the table.
Table-10 Precedence of Operators in Python
Operator Name Highest
() Parentheses
** Exponentiation
-, ~ Unary minus, bitwise complement
*, /, //, % Multiplication, Division, Floor Division,
Modulus
+, - Addition, Subtraction
<<, >> Bitwise left shift, Bitwise right shift
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
>, >=, <, <=, ==, != Relational (Comparison) operators
=, +=, -=, *=, /=, %=, //=, Assignment operators
**=
is, is not Identity operators
in, not in Membership operators
not Logical not
or Logical or
and Logical and Least
Mathematical Functions
In Python a module is a file that contains a group of objects like functions, classes or variables.
Python has a built-in module that you can use for mathematical operations. If a module is needed for
a program, it is to be imported into the program using import statement. To import math module,
import math statement needs to be used. Once this is done any functions available under math
module can be used. To refer a function under any module, the module name is to be used before the
function name. Hence to use the sqrt() function the following statement can be used
x=math.sqrt(16) #will store 4.0 in variable x.
The import statement can also be used as
import math as m
The above statement will name math module as m in the current program. The import math statement
is useful to import all the functions from the math module. On the other hand, if the programmer
wants to import only the specific functions the following statement can be used.
from math import factorial, sqrt
Here, the programmer is importing two functions factorial() and sqrt(). The programmer can use these
functions without using module names before them as
x=sqrt(16)
y=factorial(5)
Table-11 Important Math Functions
Function Description
ceil(x) Returns x value to the next higher integer. If x is an integer, then same value is
returned. Eg: ceil (4.5) returns 5
floor(x) Decreases x value to the previous integer value. If x is an integer, then same value
is returned. Eg: ceil (4.5) returns 4
degrees(x) Converts angle value of x from radians to degrees. Eg: degrees(3.14159) gives
179.998479604043
radians(x) Converts x value from degrees to radians. Eg: radians (180) gives
3.141592653589793
sin(x) Gives the sine value of x. The value of x is given in radians. Eg: sin(0.5) gives
0.47942553604203
cos(x) Gives the cosine value of x. The value of x is given in radians. Eg: cos(0.5) gives
0.8775825618903728
tan(x) Gives the tangent value of x. The value of x is given in radians. Eg: tan(0.5) gives
0.5463024898437905
exp(x) Returns exponentiation of x. it is same as e**x. Eg: exp(0.5) gives
1.6487212707001282
fabs (x) Gives the absolute value of x. Eg: fabs(-4.56) gives 4.56
factorial(x) Returns the factorial of x. Raises ‘value error’ if x is not an integer or is negative.
Eg: factorial(4) gives 24
fmod(x,y) Returns reminder of division of x and y. fmod() is preferred to calculate the
modulus of float values where % works well on integers. Eg: fmod(14.5, 3) gives
2.5
fsum(values) Returns accurate sum of floating-point values. Eg: fsum(1.5, 2.4, -3.3) returns
0.60000000000000001
modf(x) Returns float and integer values of x. Eg: modf(2.56) gives (0.56, 2)
log10(x) Returns base 10 logarithm of x. Eg: log10(5.2345) gives 0.7188752041406328
log(x, [, base]) Returns natural logarithm of x of specified base. Eg: log(5.5, 2) gives
2.4594316186372973
sqrt(x) Returns positive square root of x. Eg: sqrt(49) returns 7.0
pow(x,y) Raises x to the power of y. Eg: pow(5,3) returns 125.0
gcd(x,y) Gives greatest common devisor of x and y. Eg: gcd(25, 30) gives 5
trnuc(x) The real value of x is truncated to integer value and returned. Eg: trunc(15.5676)
returns 15
isinf(x) Returns True if x is positive or negative infinity, and False otherwise
isnan(x) Returns True if x is a NaN (Not a Number), and False otherwise.
Eg: num=float (NaN)
isnan(Num) gives True

Table-12 Constants in Math Module


Function Description
pi The mathematical constant 𝜋 = 3.141592 … with high precision
e Mathematical constant e = 2.71821… with high precision
inf A floating-point positive infinity.
nan A floating-point not a number
Example program
#To calculate are and perimeter of a circle
import math
r=int(input("Enter the radius of the circle"))
area=math.pi*r**2
p=2*math.pi*r
print("Area = %0.2f " %area, end=" ")
print("Perimeter = %0.2f " %p)
Output
Enter the radius of the circle 10
Area = 314.16 Perimeter = 62.83
UNIT – 1 Chapter -5 Control Statements
The two most commonly used statements in any programming language are as follows :
• Sequential statements: These are the statements which are executed one by one.
• Control statements: These are the statements that are executed randomly and repeatedly.
When the instructions are executed one by one by the Python interpreter. This is called sequential
execution. This type of execution is suitable only for developing simple programs. It is not suitable
for developing critical programs where complex logic is needed.
Control Statements in Python
• if statement
• if ... else statement
• if ... elif ... else statement
• while loop
• for loop
• else suite
• break statement
• continue statement
• pass statement
• assert statement
• return statement
Note: The switch statement found in many languages like C and Java is not available in Python.
The if Statement
This statement is used to execute one or more statement depending on whether a condition is True
or not.
Syntax: if condition:
statements
First, the condition is tested. If the condition is True, then the statements given after colon (:) are
executed. One or more statements can be written after colon (:). If the condition is False, then the
statements mentioned after colon are not executed.
Example:
#if statement example
num=int(input('Enter a number '))
if num==1:
print("You entered One")
It is possible to write a group of statements after colon. The group of statements in Python is called
a suite. While writing a group of statements, they are to be written with proper indentation. The
default indentation used in Python is 4 spaces.
Example:
#if suite example
str=input('Enter your answer ')
if str=='yes':
print("Your reply is positive")
print("Congratulations")
print("For taking he right decision")
every print() function mentioned after the colon starts after 4 spaces only. When there are multiple
statements with same indentation, those statements are considered as suite.
Indentation
Understanding indentation is very important in Python. Indentation refers to spaces that are used in
the beginning of a statement. The statements with same indentation belong to same group called suite.
By default Python uses 4 spaces but it can be increased or decreased by the programmers.
Example:
#if suite and indentation example
x=int(input("Enter a number")) Output when Output when Output when
y=int(input("Enter a number")) x=1, y=0 x=1, y=2 x=0, y-0
if x==1: a a end
print('a') b b
print('b') end c
if y==2: d
print('c') end
print('d')
print('End')

The if … else Statement


The if ... else statement executes a group of statements when a condition is True; otherwise, it will
execute another group of statements.
Syntax:
if condition:
statements1
else:
statements2
If the condition is True, then it will execute statements1 and if the conditions is False, then it will
execute statements2. It is advised to use 4 spaces as indentation before statements1 and statements2.
#if else example
x=int(input('Enter a number'))
if x> 0:
print(x, " is positive")
else:
print(x, " is negative")
Short Hand If ... Else
If there is only one statement to execute, one for if, and one for else, it can be put in the same line
which becomes one line if else statement:
Example:
a = 2
b = 330
print("A") if a > b else print("B")
The if ... elif ... else Statements
Sometimes, the programmer has to test multiple conditions and execute statements depending on
those conditions. if ... elif ... else statement is useful in such situations.
Syntax:
if condition1:
statements1
elif condition2:
statements2
elif condition3:
statements3
else:
statements4
When condition1 is True, the statements1 will be executed. If condition1 is false, condition2 is
evaluated. When condition2 is true statements2 will be executed. When condition2 is false,
condition3 will be evaluated. When condition3 is true statements3 will be executed. When condition3
is false the statements4 will be executed. It means that statements4 will be executed only when none
of the conditions are True. The : in each statements represents one statement or suite, and the final
‘else’ part is optional.
Example:
#demonstration of if.. elif
num=int(input("Enter a number "))
if num==0:
print("The number is ZERO")
elif num>0:
print("The number is Positive")
else:
print("The number is Negative")
The while Loop
A loop is useful to execute a set of instructions repeatedly. In Python there are two looping statements
namely while and for loops. The while loop is useful to execute a group of statements several times
repeatedly depending on whether a condition is True or False.
Syntax:
while condition:
statements
Here, 'statements' represents one statement or a suite of statements.
Python interpreter first checks the condition. If the condition is True, then it will execute the
statements written after colon (:). After executing the statements, it will go back and check the
condition again. If the condition is again found to be True, then it will again execute the statements.
Then it will go back to check the condition once again. In this way, as long as the condition is True,
Python interpreter executes the statements again and again. Once the condition is found to be False,
then it will come out of the while loop.
Example
#Display numbers from 1 to 10
Output:
x=1
1 2 3 4 5 6 7 8 9 10
while x<=10:
End of loop
print(x, end=" ")
x=x+1
print("\n End of loop")
The for Loop
The for loop is useful to iterate over the elements of a sequence. It means, the for loop can be used
to execute a group of statements repeatedly depending upon the number of elements in the sequence.
The for loop can work with sequence like string, list, tuple, range etc.
Syntax:
for var in sequence:
statements
The first element of the sequence is assigned to the variable written after 'for' and then the statements
are executed. Next, the second element of the sequence is assigned to the variable and then the
statements are executed second time. In this way, for each element of the sequence, the statements
are executed once So, the for loop is executed as many times as there are number of elements in the
sequence.
Example:
#Program to display sum of a list of numbers
lst = [10,20,30,40,50]
sum=0
for i in lst:
print(i)
sum+=i
print('Sum=', sum)
The range() function is useful to provide a sequence of numbers. range(n) gives numbers from 0 to
n-1. For example range(10) will return numbers from 0 to 9. It is possible to mention the starting and
ending values along with the range function as range(5, 10). In this case numbers from 5 to 9 are
returned. By default, the step value is 1 however it is possible to specify the step size. The step size
represents the increment in the value of variable for each iteration. For example range(1,10,2) will
five numbers from 1 to 9 in steps of 2. That means 1, 3, 5, 7, and 9 will be the output. If range value
is negative, the variable will be decremented after every iteration.
Example:
#Program to display odd numbers between 1 and 10
for i in range(1,10,2):
print(i)
Example:
#Program to display in descending order
for i in range(10,0,-1):
print(i)
List is a sequence that contains a group of elements that can store different type of elements. It is
possible to retrieve the elements of a list using for loop.
Example:
#Program to display elements of a list
lst=[10, 20, 15.5, ‘A’, ‘India’]
for ele in lst:
print(ele)
Infinite Loops
The loops that do not terminate are called as infinite loops.

Example-1 Example-2
i=1 while(True)
while(i<10) print(“Hai”)
print(i)
Both loops mentioned above are infinite loops. Infinite loops are drawbacks in a program because
when the user is caught in an infinite loop, he cannot understand how to come out of the loop. So, it
is always recommended to avoid infinite loops in any program.
Nested Loops
It is possible to write one loop inside another loop. Such loops are called nested loops.
Example
for i in range(3):
for j in range(4):
print('i=',i,'j=',j)
The else Suite
In Python, it is possible to use 'else' statement along with for loop or while loop in the form shown
in Table-12. The else suite will be always executed irrespective of the statements in the loop are
executed or not.
Table-12 Else Suite with Loops
for with else while with else Example Output
for( var in sequence): while( condition ): for i in range(5): Yes
statements statements print("Yes") Yes
else: else: else: Yes
statements statements print("No") Yes
Yes
No
The break Statement
The break statement can be used inside a for loop or while loop to come out of the loop. When
'break' is executed, the Python interpreter jumps out of the loop to process the next statement in the
program.
Example-1:
while x>=1:
print ('x=', x)
x-=1
if x==5:
break
print("Out of loop")

Example-2:
#Searching for an element in the given list
lst1=[1, 2, 3, 5, 6, 8, 10]
ele=int(input("Enter the element to be searched"))
for x in lst1:
if x==ele:
print(ele, 'Found in the given list')
break;
else:
print(ele, 'Not found in the given list')
The continue Statement
The continue statement is used in a loop to go back to the beginning of the loop. It means, when
continue is executed, the next repetition will start. When continue is executed, the subsequent
statements in the loop are not executed.
x = 0 Output:
while x<10: x= 10
x+=1 x= 9
if x>5: x= 8
continue x= 7
print ('x=', x) x=6
print("Out of loop")
The pass Statement
The pass statement does not do anything. It is used with 'if' statement or inside a loop to represent no
operation. The pass statement is used when a statement is needed syntactically but no operation is
needed. The more meaningful usage of pass statement is to inform Python interpreter not to do
anything when the result is insignificant. Sometimes, pass is used when the user doesn’t want any
code to execute. User can simply place pass where empty code is not allowed, like in loops, function
definitions, class definitions, or in if statements. Using pass statement user avoids this error.
Examples:
#pass demo Output:
x=0 x= 1
while x<=6: x= 2
x+=1 x= 3
if x>5: x= 4
pass; x=5
print("x=",x) x= 6
print("Out of While loop")

#pass demo
num_lst=[1, 2, 4, -6, 8, -9, 15, -10]
for i in num_lst:
if (i>0):
pass Output:
else:
-6 -9 -10
print(i, end=" ")
The assert Statement
The assert statement is useful to check if a particular condition is fulfilled or not. The syntax is as
follows:
assert expression, message Output:
Enter a number -9
In the above syntax, the 'message' is not compulsory.
Traceback (most recent call last):
Example:
#assert demo File "F:\Python\assert.py", line 3, in
x=int(input("Enter a number ")) <module>
assert x>0, "Wrong input entered " assert x>0, "Wrong input entered "
print("You entered", x) AssertionError: Wrong input entered
The AssertionError shown in the output is called an exception. An exception is an error that occurs
during runtime. To avoid such type of exceptions, they can be enclosed between try… and except as
follows
Example:
#assert demo Output:
x=int(input("Enter a number ")) Enter a number -9
try: Wrong input entered
assert(x>0)
print("You intered ", x)
except AssertionError:
print("Wrong input entered")
The return Statement
A function represents a group of statements to perform a task. The purpose of a function is to perform
some tasks and in many cases a function returns the result. A function starts with the keyword def that
represents the definition of the function. After 'def', the function should be written. Then the
variables are to be written in the parentheses.
def sum(a, b):
function body
After the function name : is used to separate the name with the function body. The body of a function
contains logic to perform specific task. A function is executed only when it is called. At the time of
calling a function, user should supply the arguments.
Example
#function demo
def sum(a,b):
print("Sum =", a+b)
sum(5,15)
sum(1.7, 3.9)
In the above example sum is a function that does not return the computed result. It is simply
displaying the result. In some cases, it is highly useful to write the function which returns a value. To
do this in Python the return statement is used. The return statement used inside a function returns
some value to the calling place.
Syntax: return expression
Example:
#function demo
Output:
def sum(a,b):
The Sum is 55
return a+b
result=sum(10, 45) The Sum is 102.46
print("The Sum is", result)
result=sum(56.8, 45.66)
print("The Sum is", result)

UNIT – 1 Chapter -6 Arrays in Python


Array
Array is an object that stores a group of elements of same datatype. Storing and processing a group
of elements is very easy using arrays. Arrays store only one type of data. One integer, one float and
one character cannot be stored in an array. Arrays can increase or decrease their size dynamically as
it is not necessary to declare the size of an array. The module ‘array’ is used to create and use arrays.
Advantages of Arrays
The following are some advantages of arrays:
• Arrays are similar to lists. The main difference is that arrays can store only one type of
elements; whereas, lists can store different types of elements. When dealing with a huge
number of elements, arrays use less memory than lists and they offer faster execution than
lists.
• The size of the array is not fixed in Python. Hence, it is not necessary to specify how many
elements to be stored into an array in the beginning.
• Arrays can grow or shrink in memory dynamically (during runtime).
• Arrays are useful to handle a collection of elements like a group of numbers or characters.
• Methods that are useful to process the elements of any array are available in 'array' module.
Creating an Array
Arrays can hold data of same type. The type should be specified by using a type code at the time of
creating the array object as:
arrayname = array(type code, [elements])
The type code 'i', represents integer type array where we can store integer numbers. If the type code
is 'f' then it represents float type array where we can store numbers with decimal point. The important
type codes are given in Table-13.
Table-13 The Type Codes to Create Arrays
Type code C type Minimum Size in Bytes
‘b’ Signed integer 1
‘B’ Unsigned integer 2
‘i' Signed integer 2
‘I’ Unsigned integer 2
‘l’ Signed integer 4
‘L’ Unsigned integer 4
‘f’ Floating point 4
‘d’ Double precision floating point 8
‘u’ Unicode character 2
A signed integer is one with either a plus or minus sign in front. That is it can be either positive or
negative. An unsigned integer is assumed to be positive.
Example to create an integer type array.
First write the module name 'array' and then the type code 'i' can be used for integer type array.
After that the elements should be written inside the square braces [ ] as,
a = array('i', [4, 6, 2, 9])
This is creating an array whose name is 'a' with integer type elements 4, 6, 2 and 9.
Similarly, to create a float type array, we can write:
arr = array('d', [1.5, -2.2, 3, 5.75])
The type code is 'd' which represents double type elements each taking 8 bytes memory.
Importing the Array Module
There are three ways to import the array module into our program. The first way is to import the
entire array module using import statement as,
import array
When the array module is imported, it is possible to get the 'array' class of that module that helps to
create an array.
Example:
a =array.array('i',[4,6,2,9])
Here, the first 'array' represents the module name and the next 'array' represents the class name for
which the object is created. We should understand that we are creating our array as an object of
array class.
The second way of importing the array module is to give it an alias name, as:
import array as ar
Here, the array is imported with an alternate name 'ar'. Hence, we can refer to the array class of 'ar' module as:
a =ar.array('i', [4,6,2,9])
The third way of importing the array module is to write:
from array import *
Observe the '*' symbol that represents 'all'. The meaning of this statement is this: import all (classes, objects,
variables etc) from the array module into our program. That means we are specifically importing the 'array'
class (because of * symbol) of 'array' module. So, there is no need to mention the module name before our
array name while creating it. We can create the array as:
a =array('i',[4,6,2,9]) Output:
#Python Program to create and integer array The array elements are:
import array 5
a = array.array('i', [5, 6, -7, 8]) 6
print('The array elements are:') -7
for element in a: 8
print(element)
Output:
#Python Program to create and integer array The array elements are:
from array import * 5
a = array('i', [5, 6, -7, 8]) 6
print('The array elements are:') -7
for element in a: 8
print(element) Output:
#A Python program to create an array of characters The array elements are:
from array import * a
arr = array('u', ['a','b','c','d']) b
print('The array elements are:') c
for ch in arr: d
print(ch)
It is possible to create an array from another array. Suppose arr1 is the name of an array which is
already created and arr2 is the name of the new array that is to be created from arr1. It can be written
as
arr1 = array('d', [1.5, 2.5, -3.5, 4])
arr2 = array(arr1.typecode, (a for a in arr1))
Here arr1.typecode gives the typecode character of arr1. This typecode is used for the array arr2. The
firs a in the expression a for a in arr1 represents the value that is stored in arr2. This value is obtained
from arr1 for each element in arr1. So, all elements of arr1 will be stored as they are, into arr2.
arr2 = array(arr1.typecode, (a*3 for a in arr1))
In this case, every value obtained from arr1 is multiplied by 3 and stored in arr2.
Example:
#Program to create an array from another array Output:
from array import * The elements of second array
arr1=array('d', [1.5, 2.5, -3.5, 4]) 4.5
arr2=array(arr1.typecode, (a*3 for a in arr1)) 7.5
print("The elements of second array") -10.5
for a in arr2: 12.0
print(a)
Indexing and Slicing of Arrays
An index represents the position number of an element in an array. For example, when we create the
following integer type array:
x = array('i', [10, 20, 30, 40, 50])
Python interpreter allocates 5 blocks of memory, each of 2 bytes size and stores the elements 10, 20,
30, 40 and 50 in these blocks.

To find out the number of elements in an array we can use the len() function as:
n = len(x)
Example:
#To retrieve elements of an array using index Output:
from array import * The array elements are
x = array('i', [10, 20, 30, 40, 50]) 10 20 30 40 50
n = len(x)
print('The array elements are ')
for i in range(n):
print(x[i], end=' ')
It is also possible to access the elements of array using while loop.
Example:
#To retrieve elements of an array using index
from array import *
x = array('i', [10, 20, 30, 40, 50]) Output:
n = len(x) The array elements are
i=0 10 20 30 40 50
print('The array elements are ')
while i<n:
print(x[i], end=' ')
i+=1
A slice represents a piece of the array. With the help of slicing operation, it is possible to retrieve a
piece of the array that contains a group of elements. Whereas indexing is useful to retrieve element
by element from an array, slicing is useful to retrieve a range of elements. The general format of a
slice is :
arrayname[start:stop:stride]
It is possible to eliminate any one or two from ‘start’, ‘stop’ or ‘stride’ from the above syntax. For
example arr[1:4] gives elements from first to third. Counting of elements starts from 0. All items
‘start’, ‘stop’ and ‘stride’ represent integer values either positive or negative. The item ‘stride’
represents step size excluding the starting element.
Example:
#To implement slicing Output:
from array import * array('i', [20, 30, 40])
x = array('i', [10, 20, 30, 40, array('i', [10, 20, 30, 40, 50, 60, 80])
50, 60, 80])
array('i', [10, 20, 30, 40])
y=x[1:4]
array('i', [10, 30, 50])
print(y)
40
y=x[0:]
print(y) array('i', [40, 50, 60])
y=x[:4] array('i', [10, 30, 50, 80])
print(y)
y=x[0:5:2]
print(y)
y=x[-4]
print(y)
y=x[-4: -1]
print(y)
y=x[0:7:2]
print(y)
Types of Arrays
When discussing about arrays, any programming language like C or Java offers two types of arrays.
They are:
Single dimensional arrays: These arrays represent only one row or one column of elements. For
example, marks obtained by a student in 5 subjects can be written as 'marks' array, as:
marks = array('i', [50, 60, 70, 66, 72])
The above array contains only one row of elements. Hence it is called single dimensional array or one
dimensional array.
Multi-dimensional arrays: These arrays represent more than one row and more than one column of
elements. For example, marks obtained by 3 students each one in 5 subjects can be written as 'marks'
array as:
marks = [[50, 60, 70, 66, 72], [60, 62, 71, 56, 70], [55, 59, 80, 68, 65]]
The first student's marks are written in first row. The second student's marks are in second row and
the third student's marks are in third row. In each row, the marks in 5 subjects are mentioned. Thus
this array contains 3 rows and 5 columns and hence it is called multi-dimensional array.
Each row of the above array can be again represented as a single dimensional array. Thus the above
array contains 3 single dimensional arrays. Hence, it is called a two dimensional array. A two
dimensional array is a combination of several single dimensional arrays. Similarly, a three
dimensional array is a combination of several two dimensional arrays.
In Python, we can create and work with single dimensional arrays only. So far, the examples and
methods discussed by us are applicable to single dimensional arrays. Python does not support multi-
dimensional arrays. We can construct multidimensional arrays using third party packages like numpy
(numerical python).
Python Arrays Using numpy
numpy is a package that contains several classes, functions, variables etc. to deal with scientific
calculations in Python. numpy is useful to create and also process single and multi-dimensional
arrays. In addition, numpy contains a large library of mathematical functions like linear algebra
functions and Fourier transforms. To work with numpy, we should first import numpy module into
our Python programs as:
import numpy
we can use any of the objects from that package. But, to refer to an object we should use the
format:numpy.object
#Program to create an array using numpy
import numpy
arr = numpy.array([10, 20, 30, 40, 50])
print(arr)
#Second version
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr)

#Third version
from numpy import *
arr = array([10, 20, 30, 40, 50])
print(arr)
Creating Arrays using array()
We can call array() function of numpy module to create an array. When we create an array, we can
specify the datatype of the elements either as ‘int’ or ‘float’. We can create an integer type array as:
arr = array([10, 20, 30, 40, 50], int)
We can also eliminate ‘int’ in the above statement since Python can assess the datatypes of elements.
To create an array with float type elements, we should specify ‘float’ as:
arr = array([1.5, 2.5, 3, 4, -5.1], float)
The same statement can be rewritten by eliminating ‘float’ as Python can judge the datatypes of the
elements.
In the array, if Python interpreter finds one element belonging to ‘float type’, then it will convert all
the other elements also into float type by adding a decimal point after the element as:
arr = array([10, 20, 30.1, 40])
If we display this array using print() function, we can see the array as:
[10. 20. 30.1 40.]
To create an array with character type elements, we need not specify the datatype. We can simply
write:
arr = array(['a', 'b', 'c', 'd'])
To create a string type array where can store a group of strings, we should use additional
attribute ‘dtype = str’ in the array() function as:
arr = array(['Delhi', 'Hyderabad', 'Mumbai', 'Ahmedabad'], dtype=str)
Alternately, we can omit the ‘dtype=str’ in the above statement and write it as:
arr = array(['Delhi', 'Hyderabad', 'Mumbai', 'Ahmedabad'])
#Creating string type array using numpy Output:
from numpy import * a= [1 2 3 4 5]
arr = array(['Delhi', 'Hyderabad', 'Mumbai', 'Ahmedabad'], b= [1 2 3 4 5]
dtype=str) c= [1 2 3 4 5]
print(arr)

#creating an array from another array


from numpy import *
a = array([1,2,3,4,5])
b = array(a) #create b from a using array()
c = a #create c by assigning a to c
print("a =", a)
print("b =", b)
print("c =", c)
Creating Array using linespace()
The linspace() function is used to create an array with evenly spaced points between a starting
point and ending point. The form of the linspace() function is:
linspace(start, stop, n)
‘start ’ represents the starting element and ‘stop’ represents the ending element. ‘n’ is an integer that
represents the number of parts the elements should be divided. If ‘n’ is omitted, then it is taken as 50.
Let’s take one example to understand this.
a = linspace(0, 10, 5)
In the above statement, we are creating an array ‘a’ with starting element 0 and ending element 10.
This range is divided into 5 equal parts and hence the points will be 0, 2.5, 5, 7.5 and 10. These
elements are stored into ‘a’. Remember the elements 0 and 10 are included.
from numpy import *
a = linspace(0, 10, 5) Output:
print(‘a =’, a) a= [0. 2.5 5. 10. ]
Creating Arrays using logspace
The logspace() function is similar to linspace(). The linspace()c= [1 2 3 4 produces
function 5] the evenly spaced
points. Similarly, logspace() produces evenly spaced points on a logarithmically spaced scale. The
logspace() function is used in the following format:
logspace(start, stop, n)
The logspace() function starts at a value which is 10 to the power of ‘start’ and ends at a value which
is 10 to the power of ‘stop’. If ‘n’ is not specified, then its value is taken as 50. For example, if we
write: a = logspace(1, 4, 5)
This function represents values starting from 101 to 104. These values are divided into 5 equal points
and those points are stored into the array ‘a’.
from numpy import *
a = logspace(1, 4, 5) Output:
n = len(a) 10.0 56.2 316.2 1778.3 10000
for i in range(n):
print(“ %.1f”% a[i], end=‘ ’)
Creating Arrays using arange()
The arange() function in numpy is same as range() function in Python. The arange() function is
used in the following format:
arange(start, stop, stepsize)
This creates an array with a group of elements from ‘start’ to one element prior to ‘stop’ in steps of
‘stepsize’. If the ‘stepsize’ is omitted, then it is taken as 1. If the ‘start’ is omitted, then it is taken as
0. For example,
arange(10)
will produce an array with elements 0 to 9
arange(10, 1, -1)
Since the stepsize is -1, it represents the elements in descending order from 10 to 2, as:
[10 9 8 7 6 5 4 3 2].
#Creating array with even numbers up to 10
from numpy import * Output:
a = arange(2, 11, 2) [ 2 4 6 8 10]
print(a)
Creating Arrays using zeros() and ones()
We can use the zeros() function to create an array with all zeros. The ones() function is useful to
create an array with all 1s. They are written in the following format:
zeros(n, datatype)
ones(n, datatype)
where ‘n’ represents the number of elements. we can eliminate the ‘datatype’ argument. If we do
not specify the ‘datatype’, then the default datatype used by numpy is ‘float’. See the examples:
zeros(5)
This will create an array with 5 elements all are zeros, as: [0. 0. 0. 0. 0.]. If we want this array in
integer format, we can use ‘int’ as datatype, as:
zeros(5, int)
this will create an array as: [0 0 0 0 0].
If we use ones() function, it will create an array with all elements 1. For example,
ones(5, float)
will create an array with 5 integer elements all are 1s as: [1. 1. 1. 1. 1.].
from numpy import *
a = zeros(5, int)
print(a)
b = ones(5) #default datatype is float
print(b)
a = zeros(7)
print(a)
b = ones(6,int)
print(b)
Dimensions of Arrays
The dimension of an array represents the arrangement of elements in the array. If the elements are
arranged horizontally then it is called a row and if the elements are arranged vertically then it is called
a column. When an array contains only one row or one column then it is called Single dimensional
array or one dimensional array or1D array.
Example: Output
from numpy import *
[1 2 3 4 5]
arr1=array([1,2,3,4,5])
[10 20 30]
arr2=array([10,
20,
30])
print(arr1)
print(arr2)
If an array contains more than one row and one column then it is called Two dimensional or 2D array.
from numpy import * Output
arr1=array([1,2,3],
[1 2 3 ]
[4,5,6])
print(arr1) [4 5 6]

Attributes of an Array
Numpy’s array class is called ndarray. It is also known by alias name array. Let’s remember that
there is another class ‘array’ in Python that is different from numpy’s ‘array’ class.
The ndim Attribute
The ‘ndim’ attribute represents the number of dimensions or axes of the array. The number of
dimensions is also referred to as ‘rank’. For a single dimensional array, it is 1 and for a two-
dimensional array, it is 2.
arr1 = array([1,2,3,4,5]) Output
print(arr1.ndim) 1
arr2 = array([[1,2,3], [4,5,6]])
2
print(arr2.ndim)
Output
The shape Attribute (5, )
The ‘shape’ attribute gives the shape of an array. The shape is (2, 3)
a tuple listing the number of elements along each dimension. [ [1 2]
A dimension is called an axis. For a 1D array, shape gives the [3 4]
number of elements in the row. For a 2D array, it specifies the [5 6]]
number of rows and columns in each row. We can also change
the shape using ‘shape’ attribute.
arr1 = array([1,2,3,4,5])
print(arr1.shape)
arr2 = array([[1,2,3], [4,5,6]])
print(arr2.shape)
arr2.shape(3, 2) #change shape to 3 by 2
print(arr2)
The size Attribute
The ‘size’ attribute gives the total number of elements in the array.
arr1 = array([1,2,3,4,5])
print(arr1.size) Output
arr2 = array([[1,2,3], [4,5,6]]) 5
print(arr2.size) 6
The itemsize
Attribute The ‘itemsize’ attribute gives the memory size of the array element in bytes. As we know,
1 byte is equal to 8 bits.
arr1 = array([1,2,3,4,5])
Output
4
8
print(arr1.itemsize)
arr2 = array([1.1,2.1,3.5,4,5.0])
print(arr2.itemsize)
Output
The dtype attribute 24
This attribute gives the datatype of the elements in the array.
arr1 = array([1,2,3,4,5]) Output
print(arr1.dtype) int32
The nbytes Attribute Output
The ‘nbytes’ attribute gives the total number of bytes occupied [0 1 2 3 4 5 6 7 8 9]
by an array. The total number of bytes = size of the array * item [ [0 1 2 3 4 ],
size of each element in the array. For example, [5 6 7 8 9] ]
arr2 = array([[1,2,3], [4,5,6]]) [ [0 1]
print(arr2.nbytes) [2 3]
[4 5]
The reshape() Method [6 7]
The ‘reshape()’ method is useful to change the shape of an array. [8 9]
The new array should have the same number of elements as in the
original array. For example,
arr1 = arange(10)
print(arr1) Output
arr1 = arr1.reshape(2, 5) [ [1 2 3]
print(arr1) [ 4 5 6]]
arr1 = arr1.reshape(5, 2) [1 2 3 4 5 6]
print(arr1)
The flatten() Method
The flatten() method is useful to return a copy of the array collapsed into one dimension.
arr1 = array([[1,2,3],[4,5,6]])
print(arr1)
arr1 = arr1.flatten()
print(arr1)

Working with Multi-dimensional Arrays


The 2D arrays, 3D arrays etc. are called multi-dimensional arrays. A 2D array contains more than 1
row and 1 column and it can be treated as a combination of several 1D arrays. A 2D array is also
considered as a matrix. For example, a 2D array with ‘m’ rows and ‘n’ columns is called m x n matrix.
We can create multi-dimensional arrays in the following ways:
• Using array() function
• Using ones() and zeroes() functions
• Using eye() function
• Using reshape() function
The array() Function
Numpy’sarray() function can be used to create a multidimensional array. Usually, we pass lists of
elements to this function. If we pass one list of elements to this function, then it will create a 1D
array. If we pass two lists of elements, then this function creates a 2D array.
a = array([[1,2,3,4], [5,6,7,8]])
print (a)
Even though the elements are displayed in 2 rows and 4 columns, the internal memory allocated to
all these elements would be in the form of a single row containing 8 blocks (2 x 4 = 8). The elements
are stored in the contiguous memory locations as shown below.
Output
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]

The ones() and zeros() Functions


The ones() function is useful to create a 2D array with several Output
rows and columns where all the elements will be taken as 1. The [[1. 0. 0.]
format of this function is: [0. 1. 0.]
ones((r, c), dtype) [0. 0. 1.]]
Here, ‘r’ represents the number of rows and ‘c’ represents the
number of columns. ‘dtype’ represents the datatype of the elements in the array. Just like the ones()
function, we can also use the zeros() function to create a 2D array with elements filled with zeros.
Then a 2D array with 2 rows and 4 columns will be created where all elements will be 0s
Example:
from numpy import *
arr1 = ones((3, 4), float)
arr2 = = zeros((3,4), int)
print(arr1)
print(arr2)
The eye() Function
The eye() function creates a 2D array and fills the elements in the diagonal with 1s. The general
format of using this function is:
eye(n, dtype=datatype)
This will create an array with ‘n’ rows and ‘n’ columns. The default datatype is ‘float’. For example,
eye(3) will create a 3x3 array and fills the diagonal elements with 1s.
from numpy import *
b =eye(3)
print(b)

The reshape() Function


The reshape() function has been already discussed in the previous section. We will have an
elaborate discussion about this function now. This function is useful to convert a 1D array into a
multidimensional (2D or 3D) array. The syntax of writing this function is:
reshape(arrayname, (n, r, c))
Here, ‘arrayname’ represents the name of the array whose elements to be converted. ‘n’ indicates
the number of arrays in the resultant array. ‘r’, ‘c’ indicates the
number of rows and columns, respectively. For example, we take a 1D Output
array ‘a’ with 6 elements as: [ [1 2 3 4]
a = array([1, 2, 3, 4, 5, 6]) [ 5 6 7 8 ]]
To convert ‘a’ into a 2D array using the reshape() function, we can
write:
b = reshape(a, (2, 3))
The starting two pairs of square brackets which indicate that it is a 2D array. Suppose, we write:
b = reshape(a, (3, 2))
This will convert ‘a’ into a 2D array with 3 rows and 2 columns.
Example:
from numpy import *
a = array([1, 2, 3, 4, 5, 6])
print(a) Output
b = reshape(a, (2, 3)) [ 1 2 3]
print(b) [ 4 5 6]
c = reshape(a, (3, 2))
[7 8 9 ]
print(c)
[ 1 2 3 4 5 6 7 8 9]
Indexing in Multi-dimensional Arrays
Index represents the location number. The individual elements of a 2D array can be accessed by
specifying the location number of the row and column of the element in the array as:
a[0][0] #represents 0th row and 0th column element in the array ‘a’
b[1][3] #represents 1st row and 3rd column element in the array ‘b’
Suppose ‘a’ is the array name. len(a) function will give the number of rows in the array. a[0]
represents the 0th row, a[1] represents the 1st row, etc. So, in general, a[i] represents the ith row
elements. Hence, to display only rows of the 2D array, we can write:
for i in range(len(a)):
print(a[i])
Each row may contain some columns which represent the elements. To know, how many elements
are there in a row, we can use len(a[i]). Here, if i = 0, then len(a[0]) represents the number of columns
in 0th row. Similarly if i=1, then len(a[1]) represents the number of columns in 1st row and so on. In
this way, len(a[i]) represents the number of columns in ith row. So, the following loops will access
all elements from the 2D array:
for i in range(len(a)):
for j in range(len(a[i])):
print(a[i][j], end=' ')
print()
Program to retrieve elements from 2D Array
from numpy import *
a = array([[1,2,3], [4,5,6], [7,8,9]])
for i in range(len(a)):
print(a[i]) #displays only rows
#displays element by element
for i in range(len(a)):
for j in range(len(a[i])):
print(a[i][j], end='') Output
Slicing in Multi-dimensional Arrays [1 2 3 4 5 6]
[ [ 1 2 3]
A slice represents a part or piece of the array. In the previous
[ 4 5 6] ]
sections, we already discussed about slicing in case of single
[ [ 1 2]
dimensional arrays. Now, we will see how to do slicing in case of [3 4 ]
multi-dimensional arrays, especially in 2D arrays. We take a 2D [5 6] ]
array with 3 rows and 3 columns as:
a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] )
The format of slice operator is: arrayname[start:stop:stepsize]
The default value for start is ‘c’ for stop is ‘n’ (number of elements) and step size is 1. Counting starts
from 0th position. So if not mentioned, then starting from 0th element till the last element, entire array
will be displayed.
a[:, :] or a[:] or a[: :] will display the entire 2D array.
Suppose, we want to display the 0th row from the array, we can write: a[0,:]
Suppose, we want to display 0th column of the array, we can write: a[:, 0]
If we want to retrieve only a particular element, then we have to provide both the row and column
positions. For example, to retrieve 0th row and 0th column
element, we can write: a[0:1, 0:1] Output
Similarly, to access the 1st row and 2nd column element, we can [ 1 2 3]
[ 4 5 6]
write: a[1:2, 1:2]
[7 8 9 ]
Matrices in numpy [1 5 9]
To work with matrices, numpy provides a special object called
matrix. In numpy, a matrix is a specialized 2D array that retains its 2D nature through operations.
We can create numpy matrices using the syntax: matrix-name = matrix(2D array or string)
It means, the matrix object receives a 2D array or a string that
contains elements which can be converted into a matrix. Output
For example, a 2D array with 2 rows and 3 columns as: arr = 9 [[1,
1
2, 3], [4, 5, 6]]
This array can be converted into a matrix ‘a’ as: a = matrix(arr)
Alternately, we can also pass the 2D array to matrix object as: a = matrix([[1,2,3],[4,5,6]])
Another way of creating a matrix is by passing a string with elements
Output
to matrix object as:
45
str = ‘1 2; 3 4; 5 6’
5.0
b = matrix(str)
Retrieving Diagonal Elements of a Matrix
To retrieve the diagonal elements of a matrix, we can use diagonal()
Output
function as: [ [5 4 1]
a = diagonal(matrix) [ 2 7 0] ]
The diagonal() function returns a 1D array that contains diagonal [ [1 4 5 ]
elements of the original matrix. [0 2 7 ] ]
To understand this function, we can take an example.
a = matrix('1 2 3; 4 5 6; 7 8 9')
print(a)
d = diagonal(a)
print(d)
Finding Maximum and Minimum Elements
To know the maximum element, we can use max() method and to know the minimum element, we
can use min() methods. These methods should be called using the matrix name.
a = matrix('1 2 3; 4 5 6; 7 8 9')
big = a.max()
print(big)
small = a.min()
print(small)
Finding Sum and Average of Elements
To find sum of all the elements in the matrix, we can use sum() method and to find average, we can
use mean() method. These methods should be called using the matrix name.
print(a.sum())
print(a.mean())

Sorting the Matrix


numpy provides sort() function that sorts the matrix elements into ascending order.
m = matrix([[5, 4, 1], [2, 7, 0]])
print(m)
a=sort(m)
print(a)
Observe that the sorted matrix contains the elements in each row arranged in ascending order. To
sort elements vertically (column-wise) the sort() function with axis=0 attribute is to be used.
m = matrix([[5, 4, 1], [2, 7, 0]])
print(m)
a=sort(m, axis=0)
print(a)

Output
[ [5 4 1]
[2 7 0] ]
[ [2 4 0]
[5 7 1]]

You might also like