Leela Soft Python Madhu
Data Types in Python
In-built Data types in Python:
int
complex (scientific calculation like 10+4j )
bool
float
str
bytes
bytearry
range
list
tuple
set
frozenset
dict
None
int datatype:
Integral values: ...,-2,-1,0,1,2,.....
We can represent int values in 4 ways:
1. Decimal (by default)
2. Binary
3. Octal
4. Hexa Decimal
1. Decimal(base-10) By default
0-9 (allowed digits but not start with 0)
2. Binary (base-2)
1. 0 and 1(allowed digits)
2. starts with 0 followed by 'b' or 'B'
Ex: a=0b1010,
b=0B1010
c=0B10102 #(Invalid)
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
3. Octal (base-8)
1. 0-7 (allowed digits)
2. starts with 0 followed by 'o' or 'O'
Ex: a=0o1014,
b=0O1014,
c=0o1237
d=0o1238 #(invalid)
4. Hexa Decimal (base 16)
1. 0-9 and a-f or A-F
2. prefixed with 0x or 0X
Ex: a=0x1039Af
b=0X1039Af
c=0X09ag #(invalid)
Note:
a=10
b=0o10
c=0b10
d=0x10
Output: only in decimal
Note: There is no concept like size, range for int datatype.
format() in-built function:
format(value[, format_spec]):
Convert a value to a "formatted" representation, as controlled by format specifier.
The format() method can have optional format specifications. They are separated from field
name using colon. For example, we can left-justify <, right-justify > or center ^ a string in the
given space. We can also format integers as binary, hexadecimal etc. and floats can be rounded
or displayed in the exponent format.
Format specifier's: for Integers
'b' Binary format.
'c' Character.
'd' Decimal Integer. Output the number in base 10.
'o' Octal format.
'x' Hex format. Using lower-case letters
'X' Hex format. Using upper-case letters
'n' Number.
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
For String:
's' String format
>>> format(14, 'b')
'1110'
>>> format(14, '#b')
'0b1110'
# formatting integers
>>> "Binary representation of {0} is {0:b}".format(12)
'Binary representation of 12 is 1100'
# formatting floats
>>> "Exponent representation: {0:e}".format(1566.345)
'Exponent representation: 1.566345e+03'
# round off
>>> "One third is: {0:.3f}".format(1/3)
'One third is: 0.333'
# string alignment
>>> "|{:<10}|{:^10}|{:>10}|".format('butter','bread','jam')
'|butter | bread | jam|'
Base Conversions:
We can use the following built-in functions.
✓ bin(x)
✓ oct(x)
✓ hex(x)
Note: Here 'x' is the parameter value.
1. Decimal/Octal/Hexa Decimal to Binary form:
We can use built in function bin(parameter)
Syntax: bin(x) here x may be decimal/oct/hexadecimal
Ex:1
>>> bin(10)
'0b1010'
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Ex:2
>>> bin(0o12)
'0b1010'
Ex:3
>>> bin(0xa)
'0b1010'
2. Decimal/Binary/Hexa Decimal to Octal form:
We can use built in function oct(parameter)
Syntax: oct(x)
here 'x' may be decimal/binary/hexadecimal
Ex:1
>>> oct(10)
'0o12'
Ex:2
>>> oct(0b1010)
'0o12'
Ex:3
>>> oct(0xBee)
'0o5756'
3. Decimal/Binary/Octal to Hexadecimal form:
We can use built in function hex(parameter)
Syntax: hex(x)
here 'x' may be decimal/binary/octal
Ex:1
>>> hex(10)
'0xa'
Ex:2
>>> hex(0b1010)
'0xa'
Ex:3
>>> hex(0o765)
'0x1f5'
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
float data type:
For floating point type, we can specify in the form of decimal.
Ex:
f=123.456 #valid
f=0123.456 #valid
f=0X123.456 #invalid
f=0o123.456 #invalid
f=0b123.456 #invalid
Python not supported octal/hexa/binary forms for floating point.
We can specify floating points in the Exponential form also.
Ex:
f=1.2e3 # (1.2*10^3)
>>> a=1.2e100
>>> a
1.2e+100
Characteristics of Floating-point Numbers:
Type Storage Smallest Magnitude Largest Magnitude Minimum Precision
float 64 bits 2.22507*10-308 1.79769*10+308 15 digits
complex data type:
Complex numbers have a real and imaginary part, which are each a floating point number.
Notation:
a+bj #allowed
a+jb #not allowed
here a and b are int or float type.
'a' is real part and 'b' Imaginary part
j^2=-1 or j =sqrt(-1)
To extract these parts from a complex number 'x', use x.real and x.imag.
Ex: x=10+20j
Ex: x=2.3+4.5j
x.real #(we can get real part)
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
x.imag #(we can get imaginaries part)
Example:1
>>> a=10+20j
>>> a
(10+20j)
>>> a.real
10.0
>>> a.imag
20.0
Example:2
>>> a=10.3+20.5j
>>> a
(10.3+20.5j)
>>> a.real
10.3
>>> a.imag
20.5
bool data type:
True, False
Ex:
True + True =1+1
(Internally True=1, False=0)
Ex:
True+False =1+0
Ex:
True/False (1/0 not allowed)
(ZeroDivisionError: division by zero)
str data type:
Textual data in Python is handled with str objects, or strings. Strings are immutable sequences
of Unicode code points.
We can represent the value in the form of:
single quote : str
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
double quote : string
triple quotes : multi line string literals.
Triple quoted strings may span multiple lines - all associated whitespace will be included in the
string literal.
'str' is a built-in function (like a class) which converts its argument to a string.
In python 'string' is a module which provides common string operations (like functions).
Examples:
Single quotes:
s = 'Welcome to Python'
s = 'Welcome to "Python" Classes'
Double quotes:
s = "Welcome to Python"
s = "Welcome to 'Python' Classes"
Triple quoted:
s = """Welcome to Python"""
or
s = '''Welcome to Python'''
Ex:
s='Hi Hello'
In python +ve index and -ve index is applicable.
+ve index: 0,1,2,...(left to right)
-ve index: -1,-2,...(right to left)
We can Access string elements based on index:
s[1]= 'i'
If we give out of index:
Ex: a='Hello'
a[6]
here, we get IndexError: string index out of range
Ex:1
a='Hi Hello'
print(a)
Ex:2
a="Hi Hello"
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
print(a)
Ex:3 (This is for multiple lines representation)
Using single quotation (''')
a= '''
Hi Hello
How are
you '''
print(a)
Using double quotation (""")
a="""Hi Hello
How are
you"""
print(a)
Slice Operator:
syntax:
<string_name>[begin_index : end_index : step]
Here 'begin_index' < 'end_index', it returns substring from begin_index to end_index-1
Ex:
>>>s = 'Leela'
>>>s[1:4]
>>>s[1:] #end index is optional(from start index to until end of the string.)
>>>s[:3] #start index is optional(0 index to end-1)
>>>s[:] #start and end index both are optional. it returns full string
>>>s[-1:-4] ##no output start index is high and end index is lower
>>>s[-4:-1] ##
>>>s[100] ##error
>>>s[1:100] ##no error in slice operator
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
s='python'
>>> s[::1] #by default step is 1
'python'
>>> s[::-1] #reverse the String
'nohtyp'
bytes Data Type:
The bytes data type represents a group of byte numbers just like an array.
Example:
x = [10,20,30,40]
b = bytes(x)
type(b) bytes
print(b[0]) 10
print(b[-1]) 40
for i in b : print(i)
Conclusion 1:
The only allowed values for byte data type are 0 to 256. By mistake if we are trying to provide
any other values then we will get ValueError.
Conclusion 2:
Once we create bytes data type value, we cannot change its values, otherwise we will get
TypeError.
Example:
>>> x=[10,20,30,40]
>>> b=bytes(x)
>>> b[0]=100
TypeError: 'bytes' object does not support item assignment
bytearray Data type:
The bytearray is exactly same as bytes data type except that its elements can be modified.
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Example:
x = [10, 20, 30, 40]
b = bytearray(x)
for i in b : print(i)
b[0] = 100
for i in b: print(i)
Example:
>>> x = [10,256]
>>> b = bytearray(x)
ValueError: byte must be in range(0, 256)
None Data Type:
✓ None means nothing or No value associated.
✓ If the value is not available, then to handle such type of cases None introduced.
✓ It is something like null value in Java.
Example:
def m1():
a = 10
print(m1()) #Output: None
list data type:
If we want to represent a group of values as a single entity where insertion order required to
preserve and duplicates are allowed, then we should go for list data type.
✓ Insertion order is preserved.
✓ Heterogeneous objects are allowed.
✓ Duplicates are allowed.
✓ Growable in nature.
✓ Values should be enclosed within square brackets.
Example:
list = [10, 10.5, 'Madhu', True, 10]
print(list) #[10, 10.5, 'Madhu', True, 10]
Example:
list=[10,20,30,40]
>>> list[0]
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
10
>>> list[-1]
40
>>> list[1:3]
[20, 30]
>>> list[0]=100
>>> for i in list : print(i)
List is growable in nature. i.e., based on our requirement we can increase or decrease the size.
Example:
>>> list = [10,20,30]
>>> list.append("Madhu")
>>> list
[10, 20, 30, 'Madhu']
>>> list.remove(20)
>>> list
[10, 30, 'Madhu']
>>> list2=list*2
>>> list2
[10, 30, 'Madhu', 10, 30, 'Madhu']
Note: An ordered, mutable, heterogenous collection of elements is nothing but list, where
duplicates also allowed
tuple data type:
✓ tuple data type is exactly same as list data type except that it is immutable. i.e., we
cannot change values.
✓ Tuple elements can be represented within parenthesis.
Example:
>>>t = (10,20,30,40)
>>>type(t)
<class 'tuple'>
>>>t[0]=100
TypeError: 'tuple' object does not support item assignment
>>> t.append("Madhu")
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
AttributeError: 'tuple' object has no attribute 'append'
>>> t.remove(10)
AttributeError: 'tuple' object has no attribute 'remove'
Note: tuple is the read only version of list.
range Data Type:
✓ range Data Type represents a sequence of numbers.
✓ The elements present in range Data type are not modifiable. i.e., range Data type is
immutable.
Form-1: range(10) : generate numbers from 0 to 9
Example:
>>>r=range(10)
>>>for i in r : print(i) #0 to 9
Form-2: range(10, 20) : generate numbers from 10 to 19
Example:
r = range(10,20)
for i in r : print(i) #10 to 19
Form-3: range(10,20,2) : generate numbers from 10 to 19 but with difference
by 2. Here 2 means increment value nothing but step.
Example:
r = range(10, 20, 2)
for i in r : print(i) # 10,12,14,16,18
We can access elements present in the range Data Type by using index.
r = range(10, 20)
r[0] # 10
r[15] # IndexError: range object index out of range
We cannot modify the values of range data type.
Example:
r[0] = 100
TypeError: 'range' object does not support item assignment.
We can create a list of values with range data type.
Example:
>>> l = list(range(10))
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
set Data Type:
If we want to represent a group of values without duplicates where order is not important then
we should go for set Data Type.
✓ Insertion order is not preserved
✓ Duplicates are not allowed
✓ Heterogeneous objects are allowed
✓ Index concept is not applicable
✓ It is mutable collection
✓ Growable in nature
Example:
s = {100, 0, 10, 200, 10, 'Madhu'}
print(s) # {0, 100, 'Madhu', 200, 10}
s[0] # TypeError: 'set' object does not support indexing
The set is growable in nature, based on our requirement we can increase or decrease the size.
Example:
>>> s.add(60)
>>> s
{0, 100, 'Madhu', 200, 10, 60}
>>> s.remove(100)
>>> s
{0, 'Madhu', 200, 10, 60}
frozenset Data Type:
✓ It is exactly same as set except that it is immutable.
✓ Hence, we cannot use add or remove functions.
Example:
>>> s={10,20,30,40}
>>> fs=frozenset(s)
>>> type(fs)
<class 'frozenset'>
>>> fs
frozenset({40, 10, 20, 30})
>>> for i in fs:print(i)
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
>>> fs.add(70)
AttributeError: 'frozenset' object has no attribute 'add'
>>> fs.remove(10)
AttributeError: 'frozenset' object has no attribute 'remove'
dict Data Type:
If we want to represent a group of values as key-value pairs then we should go for dict data
type.
Example:
d={101:'durga',102:'Madhu',103:'shiva'}
Duplicate keys are not allowed but values can be duplicated. If we are trying to insert an entry
with duplicate key then old value will be replaced with new value.
Example:
>>> d={101:'durga',102:'madhu',103:'shiva'}
>>> d[101]='sunny'
>>> d
101: 'sunny', 102: 'madhu', 103: 'shiva'}
We can create empty dictionary as follows
d={}
We can add key-value pairs as follows
d['a']='apple'
d['b']='banana'
print(d)
Note: dict is mutable and the order won’t be preserved.
Note:
1. In general, we can use bytes and bytearray data types to represent binary
information like images, video files etc.,
2. In Python2 long data type is available. But in Python3 it is not available and we can
represent long values also by using int type only.
3. In Python there is no char data type. Hence, we can represent char values also by
using str type.
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Constants:
Constants concept is not applicable in Python.
But it is convention to use only uppercase characters if we don’t want to change value.
Example:
MAX_VALUE = 10
MINYEAR = 1
MAXYEAR = 9999
It is just convention but we can change the value.
www.leelasoft.com Cell: 78 42 66 47 66