Python Programming
Python Programming
Python Programming
Chapter 3
DATATYPES IN PYTHON
Comments in Python
There are two types of comments in Python. single line comments and multi-line
comments.
Single line comments
These comments start with a hash symbol (#) and are useful to mention that the entire
line till the end should be treated as comment. for example,
#To find sum of two numbers
A= 10 #store 10 into variable a.
Here, the first line is starting with a # and hence the entire line is treated as a
comment. In the second line, a 10 is a statement. After this statement, # symbol starts
the comment describing that the value 10 is stored into variable 'a'. The part of this
line starting from # symbol to the end is treated as a comment.
Comments are non-executable statements. It means neither the Python compiler nor
the PVM will execute them. Comments are for the purpose of understanding human
beings and not for the compiler or PVM. Hence, they are called non-executable
statements.
Multi line comments
When we want to mark several lines as comment, then writing # symbol in the
beginning every line will be a tedious job. For example,
# This is a program to find net salary of an employee
#based on the basic salary, provident fund, house rent allowance,
#dearness allowance and income tax.
Instead of starting every line with # symbol, we can write the previous block of code
inside “”” (triple double quotes) or’’’ (triple single quotes) in the beginning and
ending of the block as:
‘’ ‘’ “
This is a program to find net salary of an employee based on the basic salary,
provident fund, house rent allowance, dearness allowance and income tax.
“““
Or
‘‘‘
2 PYTHON PROGRAMMING
This is a program to find net salary of an employee based on the basic salary,
provident fund, house rent allowance. dearness allowance and income tax.
‘‘‘
The triple double quotes (" ““) or triple single quotes (‘’’) are called 'multi line
comments' or block comments' They are used to enclose a block of lines as
comments
Docstrings
In fact, Python supports only single line comments Multi line comments are not
available un Python. The triple double quotes or triple single quotes are actually not
multi line comments but they are regular strings with the exception that they can
span multiple lines. That means memory will be allocated to these strings internally
If these strings are not assigned to any variable, then they are removed from memory
by the garbage collector and hence these can be used as comments
So, using “”” are or ‘’’ not recommended for comments by Python people since they
internally occupy memory and would waste time of the interpreter since the
interpreter has to check them.
If we write strings inside or and if these strings are written as first statements in a
module, function class or a method, then these strings are called documentation
strings or docstrings. These docstrings are useful to create an API documentation
file from a Python program An API (Application Programming Interface)
documentation file is a text file or html file that contains description of all the
features of software, language or a product When a new software is created, it is the
duty of the developers to describe all the classes, modules, functions, etc. which are
written in that software so that the user will be able to understand the software and
use it in a proper way .These descriptions are provided in a separate file either as a
text file or an html file So, we can understand that the API documentation file is like
a help file for the end user.
Let's take an example to understand how to create an API documentation file. The
following Python program contains two simple functions. The first function is add
() function that takes two numbers and displays their sum. The second one is message
() function that displays a message "Welcome to Python" A function contains a
3 PYTHON PROGRAMMING
group of statements and intends perform a specific task. In Python, a function should
start with the def keyword. After that, we should write the function name along with
parentheses as def add ().
Observe that the add (x, y) function calls a print function that displays the sum of x
and y .But it also contains documentation strings inside a pair of “””.Similarly, the
message()) function which is the second function calls a print) function that displays
the message "Welcome to Python" .This function also contains documentation
strings written inside a pair of ‘’’. At the end of this program, we are calling these
two functions. While calling the first function, we are passing two values 10 and 25
and calling it as add (10. 25). While calling the second function, we are not passing
any value We are calling it as message () only Now, consider the following program
After typing this program, save it as ex. py and then execute it as ex.py.
Result:
Sum 35
welcome to Python
4 PYTHON PROGRAMMING
In programming languages like C, Java and many other languages, the concept of
variable is connected to memory location. In all languages, a variable is imagined as
a storage box which can store some value Suppose, we write a statement as Some
memory is allocated with the name 'a' and there the value '1' is stored Here, we can
imagine the memory as a box or container that stores the value, as shown in
1
a
The effect of a = 1
Datatypes in Python
A datatype represents the type of data stored into a variable or memory. The
datatypes which are already available in Python language are called Built-in
datatypes. The datatypes which can be created by the programmers are called User-
defined datatypes.
Built-in datatypes
✓ NoneType
✓ Numeric types
✓ Sequences
✓ Sets
✓ Mappings
Python, we store 'None' to represent an empty object and its datatype is considered
as ‘None Type’.
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 the function, if no value is passed, then the default value will be taken
as 'None'. If some value is passed to the function, then that value is used by the
function. In Boolean expressions, "None' value represents False".
Numeric Types
The numeric types represent numbers. There are three sub types
✓ int
✓ float
✓ complex
The int Datatype The int datatype represents an integer number. An integer number
is a number without any decimal point or fraction part. For example, 200, -50, 0,
9888998700, etc. are treated as integer numbers. Now, let's store an integer number
-57 into a variable 'a'.
a = -57
Here 'a is called int type variable since it is storing -57 which is an integer value It
Python, there is no limit for the size of an int datatype It can store very large integer
numbers conveniently.
float Datatype
Here num is called float type variable since it is storing floating point value Floating
point numbers can also be written in scientific notation where we use 'e' or 'E' t
represent the power of 10 Here 'e’or’E’ represents ‘exponentiation’. For example,
the number 2.5 *104 is written as 2.5E4. Such numbers are also treated as floating
point numbers. For example, x = 22 55e3
Here, the float value 22 55 10 is stored into the variable 'x'. The type of the variable
will be internally taken as float type. The convenience in scientific notation is that it
is possible to represent very big numbers using less memory.
Complex Datatype
Here, the complex number 1-5.5J is assigned to the variable 'c1’. Hence, Python
interpreter takes the datatype of the variable 'c1' as complex type.
We will write a Python program (Program 1) that adds two complex numbers and
displays their sum. In this program, we store a complex number in a variable el and
another complex number in another variable 'c2' and then add them. The result of
addition is stored into 'c3 which is another complex type variable and then the value
of 'c3' is displayed by the print () function.
Program 1: A Python program to display the sum of two complex numbers
Output
C:\>python add. py
Sum (5 5+2j)
7 PYTHON PROGRAMMING
X = 15.56
int(x) # will display 15
num =15
float (num) # will display 15.0
complex(x) is used to convert x into a complex number with real part x and
imaginary part zero. For example,
n = 10
complex (n) # will display (10+0j)
complex (x, y) is used to convert x and y into a complex number such that x will be
the real part and y will be the imaginary part. For example,
a = 10
b=-5
From the previous discussion, we can understand that int(x) is converting the
datatype of x into int type and producing decimal integer number. So, we can use
int(x) to convert a value from other number systems into our decimal number system.
This is what we are trying to do in Program 2 In this program, we are going to convert
binary, octal and hexadecimal numbers into decimal integers using type conversion.
Output
C:\>python convert.py
octal 17 = 15
Binary 1110010 - 114
Hexadecimal 1c2 = 450
There is a function in the form of int (string, base) that is useful to convert a string
into a decimal integer 'string' represents the string format of the number. It should
contain integer number in string format. base' represents the base of the number
system to be used for the string. For example, base 2 indicates binary number and
base 16 indicates hexadecimal number.
For example,
str = "1c2" #string str contains a hexadecimal number
n = int (str, 16) #hence base is 16. Convert str into int
print (n) # this will display 450
9 PYTHON PROGRAMMING
Program 3: In this program, we are going to rewrite Program 2 using into function
to convert numbers from different number systems into decimal number system.
s2= "1110010"
s3= "1c2"
n =int (s1, 8)
print ('octal 17 - ', n)
n = int (s2, 2)
print ('Binary 1110010 = ‘, n)
Output
C:\>python convert.py
Octal 17 15
We can also use functions bin () for converting a number into binary number system.
The function oct() will convert a number into octal number system and the function
hex() will convert a number into hexadecimal number system. See the following
examples
a = 10
b = bin(a)
print (b) # displays Ob1010
b = oct (a)
print (b) # displays 0012
10 PYTHON PROGRAMMING
b = hex(a)
print (b)# displays Oxa
bool Datatype
The bool datatype in Python represents Boolean values. There are only two Boolean
values. True or False that can be represented by this datatype Python internally.
represents True as 1 and False as 0 A blank string like is also represented as False
Conditions will be evaluated internally to either True or False For example,
a = 10 b=20
if(a<b): print ("Hello") # displays Hello.
In the previous code, the condition a<b which is written after if is evaluated to True
and hence it will execute print("Hello").
a = 10>5 # here 'a' is treated as bool type variable
print(a) # displays True
a = 5>10
print(a) # displays False
Sequences in Python
➢ str
➢ bytes
➢ byte array
➢ list
➢ tuple
➢ range
11 PYTHON PROGRAMMING
str Datatype
strl 1=”””his is a book on Python which discusses all the topics of Core Python in a
very lucid manner." “”
str2 = ‘’’This is a book on Python which discusses all the topics of Core Python in a
very lucid manner. ‘’’
The triple double quotes or triple single quotes are useful to embed a string Inside
another string as shown below:
str=" ““This is 'Core Python' book."""
print (str) # will display: This is 'Core Python' book.
The slice operator represents square brackets [and]to retrieve pieces of a string. For
example, the characters in a string are counted from 0 onwards. Hence, str [0]
indicates the 0 character or beginning character in the string. See the examples
below:
S= ‘welcome to Core Python' # this is the original string
print(s)
Welcome to Core Python
Core Python
print(s[-1]) # display first character from the end
n
The repetition operator is denoted by" symbol and useful to repeat the string for
several times. For example s*n repeats the string for n times See the example print
(s*2)
bytes Datatype
The bytes datatype represents a group of byte numbers just like an array does. A byte
number any positive integer from 0 to 255 (inclusive) bytes array can store numbers
in the range from 0 to 255 and it cannot even store negative numbers. For example,
elements [10, 20, 0, 40, 15] # this is a list of byte numbers
We cannot modify or edit any element in the bytes type array For example, x[0] =
55 gives an error Here we are trying to replace 0th element (ie 10) by 55 which is
not allowed Now, let's write a Python program (Program 4) to create a bytes type
array with a group of elements and then display the elements using a for loop. In this
program, we are using a for loop as
for i in x: print(i)
It means, if is found in the array 'x' then display i value using print () function.
Remember, we need not declare the datatypes of variables in Python. Hence, we
need not. tell which type of variable ‘i' is. In the above loop, 'i' stores each element
of the array 'x' and with every element, print(i) will be executed once Hence, print(i)
displays all elements of the array 'x' We will discuss for loop in detail in the next
chapter
13 PYTHON PROGRAMMING
Program 4: A Python program to create a byte type array, read and display the
elements of the array
list Datatype
will create a list with different types of elements. The slicing operation like (0 31
represents elements from 0th to 2nd positions,
tuple Datatype
The individual elements of the tuple can be referenced using square braces as
tpl[0],tpl[1], tpl[2], Now, if we try to modify the 0th element as
Sets
✓ set datatype
✓ frozenset datatype
set Datatype
To create a set, we should enter the elements separated by commas inside curly
braces { }.
S= {10, 20, 30, 20, 50}print (S) # may display (50, 10, 20, 30)
Please observe that the set 's' is not maintaining the order of the elements. We entered
the elements in the order 10, 20, 30, 20 and 50. But it is showing another order. Also,
we repeated the element 20 in the set, but it has stored only one 20. We can use the
set () function to create a set as
Ch= set("Hello")
1st= [1,2,5,4,3]
s=set(1st)
print (s) # may display {1, 2, 3, 4, 5)
Since sets are unordered, we cannot retrieve the elements using indexing or slicing
operations. For example, the following statements will give error messages:
15 PYTHON PROGRAMMING
s. update ([50,60])
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 frozenset
cannot be modified. We can create a frozenset by passing a set to frozenset ()
function as:
S={(50,60,70,80,90}
print (fs) #may display frozenset ([80, 90, 50, 60, 70))
Another way of creating a frozenset is by passing a string (a group of characters) to
the frozenset () function as
However, update () and remove () methods will not work on frozen sets since they
cannot be modified or updated.
16 PYTHON PROGRAMMING
Mapping Types
A map represents a group of elements in the form of key value pairs so that when
the key is given, we can retrieve the value associated with it. The dict datatype is an
example for a map. The 'dict’ represents a 'dictionary' that contains pairs of elements
such that the first element represents the key and the next one becomes its value. The
key and its value should be separated by a colon (:) and every pair should be
separated by al comma. All the elements should be enclosed inside curly brackets
{}. We can create a dictionary by typing the roll numbers and names of students.
Here, roll numbers are keys and names will become values. We write these key value
pairs inside curly braces as
Here, d is the name of the dictionary 10 is the key and its associated value is 'Kamal.
The next key is 11 and its value is 'Pranav' Similarly 12 is the key and 'Hasini' is it
value 13 is the key and 'Anup' is the value and 14 is the key and Reethu' is the value.
We can create an empty dictionary without any elements as
D= {}
Later, we can store the key and values into d as
d [10] =” Kamal “
d [11] =” Pranav”
In the preceding statements, 10 represents the key and Kamal' is its value Similarly
11 represents the key and its value is 'Pranav'.
Now, if we write print (d)
Literals in Python
A literal is a constant value that is stored into a variable in a program Observe the
following statement,
a = 15
Here, 'a' is the variable into which the constant value '15' is stored Hence, the value
15 is called "literal' Since 15 indicates integer value, it is called integer literal' The
following are different types of literals in Python.
1. Numeric literals.
2. Boolean literals
3. String literals
Numeric Literals
These literals represent numbers. Please observe the different types of numeric
literals available in Python.
450, -15 -Integer literal
0557-octal literal
OB110101-Binary literal
18+3J-Complex literal
Boolean Literals
Boolean literals are the True or False values stored into a bool type variable.
18 PYTHON PROGRAMMING
String Literals
A group of characters is called a string literal These string literals are enclosed in
single quotes () or double quotes (") or triple quotes (" or). In Python, there is no
difference between single quoted strings and double quoted strings. Single or double
quoted strings should end in the same line as
SI ‘This is first Indian book'
S2 "Core Python"
When a string literal extends beyond a single line, we should go for triple quotes as:
s1 =’’’This is first Indian book on
Core Python exploring all important and useful features’’’
To know the datatype of a variable or object, we can use the type () function. For
example, type(a) displays the datatype of the variable 'a'.
a = 15
print (type(a))
<class 'int'>
Since we are storing an integer number 15 into variable 'a', the type of 'a' is assumed
by the Python interpreter as 'int' Observe the last line It shows class int' It means the
variable 'a' is an object of the class int' It means int' is treated as a class. Every
datatype is treated as an object internally by Python.
Keywords
Reserved words are the words that are already reserved for some particular purpose
in the Python language. The names of these reserved words should not be used as
identifier. The following are the reserved words available in Python.
19 PYTHON PROGRAMMING
And del elif else except from global nonlocal try as not while assert break if or pass with
Yield False class import exec in print continue def finally is raise for lambda True return
Package names should be written in all lower case letters When multiple words are
used for a name, we should separate them using an underscore ( _).
Modules: Modules names should be written in all lower-case letters When multiple
words are used for a name, we should separate them using an underscore (__).
Classes: Each word of a class name should start with a capital letter This rule is
applicable for the classes created by us Python's built-in class names use all
lowercase words When a class represents exception, then its name should end with
at word 'Error'.
Global variables or Module-level variables: Global variables names should be all
lower-case letters When multiple words are used for a name, we should separate
them using an underscore (_).
Instance variables: Instance variables names should be all lower-case letters. When.
Multiple words are used for a name, we should separate them using an underscore
(_). Non-public instance variable name should begin with an underscore.
Functions: Function names should be all lower-case letters When multiple words
are used for a name, we should separate them using an underscore (_)
Methods: Method names should be all lower-case letters When multiple words are
used for a name, we should separate them using an 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'.
20 PYTHON PROGRAMMING
Constants: Constants names should be written in all capital letters. If a constant has
several words, then each word should be separated by an 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 for example,
_init_(self) is a function used in a class to initialize variables
Points to Remember
✓ Python has only single line comments starting with a hash symbol (#)
✓ Triple single quotes ("") or triple doubles quotes ("") can be used to create
multi line comments.
✓ Docstrings are the strings written inside triple single quotes or triple double
quotes and as first statements in a function, class or a method. These
docstrings are useful to create API documentation file that contains the
description of all features of a program or software
✓ A datatype represents the type of data stored into a variable. The data stored
into the variable is called literal
✓ There are four built-in datatypes in Python They are numeric types, sequences,
sets and mappings A binary literal is represented using Ob or OB in the
beginning of a number.
✓ A list is a dynamically growing array that can store different types of elements.
Lists are written using square brackets [1 A tuple is similar to a list but its
elements cannot be modified A tuple uses parentheses () to enclose its
elements.
✓ The rules related to writing names for packages, modules, classes, functions,
variables, etc., are called naming conventions.