lecture 3 datatypes of python
lecture 3 datatypes of python
Datatypes in Python
By
Dr. Sunita Varma
Comments in Python
• Single line comment
• Comments start with hash symbol #
• Entire line till end should be treated as comment
• # to find sum of two numbers
• a = 10 # store 10 into variable a
• Comments are non-executable statements
• Neither Python compiler nor PVM will execute them
• Comments are for purpose of understanding human beings
Comments in Python
• Multi line comment
• To mark several lines as comment then writing # symbol in beginning of every line
will be 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
• Multiline comment can be written by using triple double quotes ””” or
triple single quotes ‘’’ in the beginning and ending of block
• “”” 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
• ‘’’ 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 ‘’’
Docstrings
• Python supports only single line comments
• Multi line comments are not available in python
• Triple doble quotes or triple single quotes are actually not multi line
comments but they are regular strings with exception that they span
multiple line
• Memory will be allocated to these strings internally
• If these strings are not assigned to any variable than they are
removed from memory by garbage collector and the can be used as
comments
Docstrings
• Using “”” are ‘’’ or not recommended for comments since they
internally occupy memory and would waste time of interpreter since
interpreter has to check them
• If strings inside “”” or ‘’’ are written as first statements in module
functions class or method then these strings are called
documentation strings or docstrings
• docstrings are useful to create API documentation file from python
program
• API documentation file is text file or html file that contains
description of all features of software language or product
Docstrings
• When new software is created it is duty of developers to describe all
classes modules functions etc which are written in that software so
that user will be able to understand software and use it in proper way
• Descriptions are provided in separate file either as text file or html file
so user can understand that API documentation files is like help file
for end user
Docstrings
• Example:
• # program with two functions
• def add(x,y):
• “””
This functions takes two numbers and finds their sum
It displays the sum as result.
• “””
Print(“Sum =“, (x+y))
• def message():
• “””
This function display message.
This welcome message to the user
“””
print(“welcome to core python”)
• # now call the functions
add(10,25)
message()
Docstrings
• C:\>python ex.py
• sum = 35
• Wel come to python
Docstrings
• For creating API documentation file program is executed by using
following command:
• C:\python –m pydoc –w ex
sum = 35
welcome to python
wrote to ex.html
a
How python sees Variables
• For every variable created there will be new box created with variable
name to store value
• If value is changed in variable then box will updated with new value
• a = 2;
2 2
b a
• b = oct(a)
• print(b)
• b = hex(a)
• print(b)
Bool datatype
• Bool datatype in python represents Boolean values
• There are only two Boolean values True or False that can be represented by
bool datatype
• Python internally represents True as 1 and False as 0
• Condition will be evaluated internally to either True or False
• For example:
• a = 10
• b = 20
• if (a>b):
• Print(a)
• else:
• Print(b)
Sequence in Python
• Sequence represents group of elements or items
• For example a group of integer number form sequence
• There are six types of sequences in python
❑str
❑bytes
❑bytearry
❑list
❑tuple
❑range
Str datatype
• In python str represents string type datatype
• String is represented by group of characters
• String are enclosed in single quotes or double quotes
• str = “welcome”
• str = ‘welcome’
• String can also be written in inside “”” triple double quotes or ‘’’ triple single quotes to span of group of lines
including spaces
• str1 = “””this is book on python which
discusses all the topics of core python
in a vey lucid manner”””
• str2 = ‘’’this is book on python which
discusses all the topics of core python
in a vey lucid manner’’’
Str datatype
• Triple double quotes or triple single quotes are useful to embed string into
another string
• str = “”” This is a ‘core python’ book”””
• print(str)
• str = ‘’’This is a “core python” book’’’
• Slice operator represents square brackets [] to retrieve pieces of string
• Characters in string counted from 0 onwards
• s = ‘Welcome to core python’
• print(s)
• print(s[0])
• print(s[3:7])
• print(s[11:])
• print(s[-1])
Str datatype
• Repetition operator is denoted by * symbol and useful to repeat
string for several times
• s*n repeats string for n times
• print(s*2)
Bytes datatype
• Bytes datatype represents group of byte numbers just like array does
• Byte number is any positive integer from 0 to 255
• It cannot store negative number
• For example
• elements = [10, 20, 0, 40, 15]
• x = bytes(elements)
• Print(x[0])
• Element cannot modify or edit in any element in bytes type array
• For example:
• X[0] = 55 gives error
Bytes datatype
• Program 4:
• Write a python program to create a byte array, read and display the
elements of the array
Bytearray Datatype
• Bytearray datatype is similar to bytes datatype
• Difference is that bytes type array cannot be modified but bytearray
type array can be modified
• Bytearray function is used to create byte type array
• For example:
• elements = [10, 20, 0, 40, 15]
• x = bytearray(elements)
• Print(x[0])
• x[0] = 88
• x[1] = 99
Bytearray Datatype
• Program 5: Write a program to create a bytearry and modify the first
two elements. Also retrieve the elements of array
list Datatype
• List represents group of elements
• Python are similar to arrays in C and Java
• Main difference between list and array is that list can store different
types of elements but array store only one type of elements
• List can grow dynamically in memory
• Size of array is fixed and they cannot grow at runtime
• Lists are represented using square brackets [] and elements are
written in [] separated by commas
• List = [10, -20, 15.5, ‘vijay’, “Marry”]
list Datatype
• Program 6: write a python program to print the
1. First element of list
2. First three element of list
3. Second last element of list
4. Print the list 4 times
Tuple Datatype
• Tuple is similar to list
• Tuple contains group of elements which can be of different types
• Elements in tuple are separated by commas and enclosed in
parentheses ()
• List of elements can be modified it is not possible to modify tuple
elements
• Tuple is a read only list
• For example:
• Tp1 = (10, -20, 15.5, ‘Vijay’, “Marry)
• Individual elements of tuple can be referenced using square braces as
tp1[0] tp1[1]……
• Tp1[0] = 99 gives error
Tuple Datatype
• Program 7: write a python program to print the
1. Third element of tuple
2. 2nd to 4th element of tuple
3. last element of tuple
4. Print the tuple 4 times
range Datatype
• Range data type represents sequence of numbers
• Numbers in range are not modifiable
• Generally range is used for generating for loop for specific number of
times
• For example:
• r = range(10)
• Range object is created with numbers starting from 0 to 9
• This number can be displayed by using for loop
• r = range(10,40,2)
• for i in r: print(i)
• lst = list(range(10))
• print(lst)
Sets
• Set is an unordered collection of elements
• Order of elements is not maintained in sets
• Elements may not appear in same order as they are entered into set
• Set does not accept duplicate elements
• Two sub types in sets:
❑Set datatypes
❑Frozen set datatype
set Datatype
• To create set elements are entered separated by commas inside curly
braces{}
• s = {10, 20, 30, 20, 50}
• Print(s)
• Sets are not maintaining order of elements
• Elements are not repeated in set
• ch = set(“Hello”)
• print(ch)
• lst [1,2,5,4,3]
• s = set(lst)
• print(s)
set Datatype
• Sets are unordered elements can not retrieve using indexing or slicing
operation
• For example:
• print(s[0])
• print(s[0:2])
• Gives error
• update() method is used to add elements to set as:
• s.update([50,60])
• print(s)
• remove() method is used to remove any particular element from set
• s.remove(50)
• print(s)
frozenset Datatype
• frozenset datatype is same as set datatype
• Main difference is that elements in set datatype can be modified
whereas elements of frozenset cannot be modified
• frozenset is created by passing set to frozenset() function as
• s = {50,60,70,80,90}
• print(s)
• fs = frozenset(s)
• Print(fs)
• Another way of creating frozenset is by passing string to frozenset()
function as:
• fs = frozenset(“abcdefg”)
• print(fs)
Mapping Types
• Map represents group of elements in form of key value pairs so that when key is given
associated value can be retrieved
• Dict datatype is example for map
• Dict represents dictionary that contains pairs of element such that first element
represents key and next one becomes its value
• Key and its value should be separated by colon : and every pair should be separated by
comma
• All elements should be enclosed inside curly brackets{}
• Dictionary is created for student roll number and names
• Roll number are keys and names of students are values
• d = { 10: ‘kamal’, 11: ‘paranav’, 12: ‘hasini’, 13: ‘Anup’, 14: ‘Reethu’}
• D = {} empty dictionary
• Key and values are stored in dictionary as
• d[10] = ‘kamal’
• d[11] = ‘paranav’
• Print(d)
Mapping Types
• Program 8: write a program to display
• keys of dictionary
• Values of dictionary
• Change the value of key
• Delete a key
Literals in Python
• Literal is constant value that is stored into variable in program
• a = 15
• Types of literal
❑Numerical literals
❑Boolean literals
❑String literals
Numeric literals
Literal name
450, -15 Integer literal
3.14286, -10.6, 1.25E4 Float literal
0x5A1C Hexadecimal literal
0o557 Octal literal
0B110101 Binary literal
18+3J Complex literal
Boolean Literals
• Boolean literals are TRUE and False values stored into bool type
variable
String Literals
• Group of characters is called string literals
• String literals are enclosed in single quotes ‘ or double quotes “ or triple quotes
“”” in python there is no difference between single quoted strings and double
quoted strings
• Single and double quoted strings should end in same line
• s1 = ‘This is a first Indian Book’
• s2 = “core python”
• When string literal extends beyond single line triple quotes are used
• s1 =‘’’This is first Indian book on
core python exploring all important
And useful features’’’
• s2 = “”” ’This is first Indian book on
core python exploring all important
And useful features”””
String Literals
• When string spans in more than one line adding backslash \ will join
next string to it
• For example:
• Str = “This is first line and \
This will be continued with first line”
print(str)
Escape characters like \n can be used inside string literal
str = “This is \npython”
print(str)
Escape characters escape normal meaning and are useful to perform
different task
When \n is written it will throw cursor to new line
String Literals
• Import escape characters in strings