UNIT - 1 Python
UNIT - 1 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.
▪ 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)
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
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)
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)
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)
Output
[ [5 4 1]
[2 7 0] ]
[ [2 4 0]
[5 7 1]]