3. Data Types
3. Data Types
In Python we are not required to specify the type explicitly. Based on value
provided, the type will be assigned automatically.
1. int
2. float
3.complex
4.bool
5.str
6.bytes
7.bytearray
8.range
9.list
10.tuple
11.set
12.frozenset
13.dict
14.None
1. int data type: We can use int data type to represent whole numbers
(integral values)
Eg: a=10
type(a) #int
Note: In Python2 we have long data type to represent very large integral values.
But in Python3 there is no long type explicitly and we can represent long values
also by using int type only.
1. Decimal form
2. Binary form
3. Octal form
Eg: a =10
2. Binary form(Base-2): The allowed digits are : 0 & 1 Literal value should be
prefixed with 0b or 0B
Eg: a =0XFACE
a=0XBeef
a =0XBeer
Note: Being a programmer we can specify literal values in decimal, binary, octal
and hexa decimal forms. But PVM will always provide values only in decimal form.
a=10
b=0o10
c=0X10
d=0B10
print(a)10
print(b)8
print(c)16
print(d)2
Base Conversions Python provide the following in-built functions for base
conversions
'0b1111'
3) >>> bin(0o11)
'0b1001'
5) >>> bin(0X10)
'0b10000'
Eg:
>>> oct(10)
'0o12'
>>> oct(0B1111)
'0o17'
>>> oct(0X123)
'0o443'
3. hex():
We can use hex() to convert from any base to hexadecimal
Eg:
>>> hex(100)
'0x64'
>>> hex(0B111111)
'0x3f'
>>> hex(0o12345)
'0x14e5'
2. float data type: We can use float data type to represent floating point
values (decimal values)
Eg: f=1.234
type(f) float
We can also represent floating point values by using exponential form (scientific
notation)
Eg: f=1.2e3
print(f) 1200.0
instead of 'e' we can use 'E'
The main advantage of exponential form is we can represent big values in less
memory.
Note: We can represent int values in decimal, binary, octal and hexa decimal
forms. But we can represent float values only by using decimal form.
Eg:
>>> f=0B11.01
File "<stdin>", line 1
f=0B11.01
^
SyntaxError: invalid syntax
>>> f=0o123.456
SyntaxError: invalid syntax
>>> f=0X123.456
SyntaxError: invalid syntax
>>> a=0B11+5j
>>> a
(3+5j)
>>> a=3+0B11j
SyntaxError: invalid syntax
>>> print(c)
(30+4j)
>>> type(c)
<class 'complex'>
Note: Complex data type has some inbuilt attributes to retrieve the real part
and imaginary part
c=10.5+3.6j
c.real==>10.5
c.imag==>3.6
We can use complex type generally in scientific Applications and electrical
engineering Applications.
4. bool data type: We can use this data type to represent boolean values.
The only allowed values for this data type are:
True and False
Internally Python represents True as 1 and False as 0
b=True
type(b) =>bool
Eg:
a=10
b=20
c=a<b
print(c)==>True
True+True==>2
True-False==>1
5. str type:
str represents String data type. A String is a sequence of characters enclosed
within single quotes or double quotes.
s1='piemr'
s1=" piemr "
By using single quotes or double quotes we cannot represent multi line string
literals.
s1="piemr indore"
For this requirement we should go for triple single quotes(''') or triple double
quotes(""")
s1=''' piemr
indore '''
s1="""''' piemr
indore """
We can also use triple quotes to use single quote or double quote in our String.
''' This is " character'''
Slicing of Strings:
slice means a piece[ ] operator is called slice operator, which can be used to
retrieve parts of String.
In Python Strings follows zero based index.
>>> s="piemr"
>>> s[0]
'p'
>>> s[1]
'i'
>>> s[-1]
'r'
>>> s[40]
IndexError: string index out of range
>>> s[1:40]
'iemr'
>>> s[1:]
' iemr '
>>> s[:4]
'piem'
>>> s[:]
'piemr'
>>> s*3
'piemrpiemrpiemr'
>>> len(s)
5
Note:
1. In Python the following data types are considered as Fundamental Data types
1. int
2. float
3. complex
4. bool
5. str
2. In Python,we can represent char values also by using str type and explicitly char
type is not available.
Eg:
>>> c='a'
>>> type(c)
<class 'str'>
3. long Data Type is available in Python2 but not in Python3. In Python3 long
values also we can represent by using int type only.
4. In Python we can present char Value also by using str Type and explicitly char
Type is not available.
Type Casting
We can convert one type value to another type. This conversion is called
Typecasting or Type coersion.
The following are various inbuilt functions for type casting.
1. int()
2. float()
3. complex()
4. bool()
5. str()
int():
We can use this function to convert values from other types to int
Eg:
>>> int(123.987)
123
>>> int(10+5j)
TypeError: can't convert complex to int
>>> int(True)
1
>>> int(False)
0
>>> int("10")
10
>>> int("10.5")
ValueError: invalid literal for int() with base 10: '10.5'
>>> int("ten")
ValueError: invalid literal for int() with base 10: 'ten'
>>> int("0B1111")
ValueError: invalid literal for int() with base 10: '0B1111'
Note:
1. We can convert from any type to int except complex type.
2. If we want to convert str type to int type, compulsary str should contain only
integral value and should be specified in base-10
float():
We can use float() function to convert other type values to float type.
>>> float(10)
10.0
>>> float(10+5j)
TypeError: can't convert complex to float
>>> float(True)
1.0
>>> float(False)
0.0
>>> float("10")
10.0
>>> float("10.5")
10.5
>>> float("ten")
ValueError: could not convert string to float: 'ten'
>>> float("0B1111")
ValueError: could not convert string to float: '0B1111'
Note:
1. We can convert any type value to float type except complex type.
2. Whenever we are trying to convert str type to float type compulsary str should
be either integral or floating point literal and should be specified only in base-10.
complex():
We can use complex() function to convert other types to complex type.
Form-1: complex(x)
We can use this function to convert x into complex number with real part x and
imaginary part 0.
Eg:
complex(10)==>10+0j
complex(10.5)===>10.5+0j
complex(True)==>1+0j
complex(False)==>0j
complex("10")==>10+0j
complex("10.5")==>10.5+0j
complex("ten")
ValueError: complex() arg is a malformed string
Form-2: complex(x,y)
We can use this method to convert x and y into complex number such that x will
be real part and y will be imaginary part.
Eg: complex(10,-2)==>10-2j
complex(True,False)==>1+0j
bool():
We can use this function to convert other type values to bool type.
Eg:
bool(0)==>False
bool(1)==>True
bool(10)===>True
bool(10.5)===>True
bool(0.0)==>False
bool(10-2j)==>True
bool(0+1.5j)==>True
bool(0+0j)==>False
bool("True")==>True
bool("False")==>True
bool(" ")==>False
str():
We can use this method to convert other type values to str type
Eg:
>>> str(10)
'10'
>>> str(10.5)
'10.5'
>>> str(10+5j)
'(10+5j)'
>>> str(True)
'True'
In Python if a new object is required, then PVM won’t create object immediately.
First it will check is any object available with the required content or not. If
available then existing object will be reused. If it is not available then only a new
object will be created.
The advantage of this approach is memory utilization and performance will be
improved. But the problem in this approach is, several references pointing to the
same object, by using one reference if we are allowed to change the content in
the existing object then the remaining references will be effected. To prevent this
immutability concept is required.
According to this once creates an object we are not allowed to change content. If
we are trying to change with those changes a new object will be created.
Eg:
>>> a=10
>>> b=10
>>> a is b
True
>>> id(a)
1572353952
>>> id(b)
1572353952
Eg:
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)
10
20
30
40
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 value error.
Conclusion 2:
Once we creates bytes data type value, we cannot change its values, otherwise
we will get TypeError.
Eg:
>>> x=[10,20,30,40]
>>> b=bytes(x)
>>> b[0]=100
TypeError: 'bytes' object does not support item assignment
Eg:
list=[10,10.5,'piemr',True,10]
print(list) # [10,10.5,'piemr',True,10]
Eg:
list=[10,20,30,40]
>>> list[0]
10
>>> list[-1]
40
>>> list[1:3]
[20, 30]
>>> list[0]=100
>>> for i in list:print(i)
100
20
30
40
list is growable in nature. i.e based on our requirement we can increase or
decrease the size.
>>> list=[10,20,30]
>>> list.append("piemr")
>>> list
[10, 20, 30, ' piemr ']
>>> list.remove(20)
>>> list
[10, 30, ' piemr ']
>>> list2=list*2
>>> list2
[10, 30, ' piemr ', 10, 30, ' piemr ']
Eg:
t=(10,20,30,40)
type(t)
<class 'tuple'>
t[0]=100
TypeError: 'tuple' object does not support item assignment
>>> t.append("piemr")
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
Form-2: range(10,20)
generate numbers from 10 to 19
r = range(10,20)
for i in r : print(i) 10 to 19
Form-3: range(10,20,2)
2 means increment value
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