__Data Types__

- Data Type represent the type of data present inside a variable.

- In Python we are not required to specify the type explicitly. Based on value provided,the type will be assigned automatically.Hence Python is Dynamically Typed Language.

**Python contains the following inbuilt data types**

**int****float****complex****bool****str****bytes****bytearray****range****list****tuple****set****frozenset****dict****None**

** Note:** Python contains several inbuilt functions

**1.type(**) to check the type of variable

**2. id()** to get address of object

**3. print() **to print the value

- In Python everything is object

__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.

We can represent int values in the following ways

- Decimal form
- Binary form
- Octal form
- Hexa decimal form

__Decimal form(base-10):__

- It is the default number system in Python
- The allowed digits are: 0 to 9

Ex: a =10

__Binary form(Base-2):__

- The allowed digits are : 0 & 1
- Literal value should be prefixed with 0b or 0B

**E**x: a = 0B1111

a =0B123

a=b111

__Octal Form(Base-8):__

- The allowed digits are : 0 to 7
- Literal value should be prefixed with 0o or 0O.

**Ex**: a=0o123

a=0o786

__Hexa Decimal Form(Base-16):__

- The allowed digits are : 0 to 9, a-f (both lower and upper cases are allowed) Literal value should be prefixed with 0x or 0X

Ex:

=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.

**bin():**We can use bin() to convert from any base to binary

Ex:

```
>>> bin(15)
'0b1111'
>>> bin(0o11)
'0b1001'
>>> bin(0X10)
'0b10000'
```

**oct():**We can use oct() to convert from any base to octal

Ex:

```
>>> oct(10)
'0o12'
>>> oct(0B1111)
'0o17'
>>> oct(0X123)
'0o443'
```

**hex():**We can use hex() to convert from any base to hexa decimal

Ex:

```
>>> hex(100)
'0x64'
>>> hex(0B111111)
'0x3f'
>>> hex(0o12345)
'0x14e5'
```

__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.

__Complex Data Type:__

A complex number is of the form

Ex:

3+5j

10+5.5j

0.5+0.1j

- In the real part if we use int value then we can specify that either by decimal, octal, binary or hexa decimal form.
- But imaginary part should be specified only by using decimal form. a=0B11+5j

a

(3+5j)

a=3+0B11j

SyntaxError: invalid syntax

Even we can perform operations on complex type values.

>>> a=10+1.5j

>>> b=20+2.5j

>>> c=a+b

>>> print(c)

(30+4j)

>>> type(c)

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.

**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**True**

True+True==>2

True-False==>1

__str type:__

str represents String data type.

A String is a sequence of characters enclosed within single quotes or double quotes.

s1=’seedgroup’

s1=”seedgroup”

By using single quotes or double quotes we cannot represent multi line string literals.

s1=”seed

group”

For this requirement we should go for triple single quotes(”’) or triple double quotes(“””)

s1=”’seed

gr0up”’

s1=”””seed

group”””

We can also use triple quotes to use single quote or double quote in our String.

This is ” character”’ ‘ This i ” Character ‘

We can embed one string in another string

”’This “Python class very helpful” for java students”’

__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.
- The index can be either +ve or -ve.

+ve index means forward direction from Left to Right -ve index means backward direction from Right to Left

…..

>>> s=”singh”

>>> s[0]

‘s’

>>> s[1]

‘i’

>>> s[-1]

‘h’

>>> s[40]

IndexError: string index out of range

>>> s[1:40]

‘ingh’

>>> s[1:]

‘ingh’

>>> s[:4]

‘sing’

>>> s[:]

‘singh’

>>> s*3

‘singhsinghsingh’

>>> len(s)

5

__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.

**int()****float()****complex()****bool()****str()**

__int():__

We can use this function to convert values from other types to int

Ex:

>>> 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:**

- We can convert from any type to int except complex type.
- 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.

```
Ex.
>>> 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:

- We can convert any type value to float type except complex type.
- 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.

Ex:

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.

Ex:

bool(0)==>False

bool(1)==>True

bool(10)===>True

bool(10.5)===>True

bool(0.178)==>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

**bool(x)**

`if x is int datatype`

- 0 means False
- Non-zero means True.

If x is Float datatype

- If total number value is zero then the result is False otherwise the result is True.

If x is Complex Datatype

- If both real and imaginary parts are zero i.e.0+0j then the result is False otherwise the result is True.

If x is str datatype

- If x is empty string then the result is False otherwise the result is True.

**str():**We can use this method to convert other type values to str type

Ex:

>>> str(10)

'10'

>>> str(10.5)

'10.5'

>>> str(10+5j)

'(10+5j)'

>>> str(True)

'True'

bytes Data Type:

bytes data type represens a group of byte numbers just like an array.

Ex:

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.

Ex:

>>> x=[10,20,30,40]

>>> b=bytes(x)

>>> b[0]=100

TypeError: ‘bytes’ object does not support item assignment

bytearray Data type:

bytearray is exactly same as bytes data type except that its elements can be modified.

Ex 1:

x=[10,20,30,40]

b = bytearray(x)

for i in b : print(i)

10

```
20
30
40
b[0]=100
for i in b: print(i)
100
20
30
40
```

Ex 2:

>>> x =[10,256]

>>> b = bytearray(x)

ValueError: byte must be in range(0, 256)

**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.

Ex:

list=[10,10.5,'seed',True,10]

print(list) # [10,10.5,'durga',True,10]

Ex

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
```

List is grow able in nature. i.e. based on our requirement we can increase or decrease the size.

```
>>> list=[10,20,30]
>>> list.append("seed")
>>> list
[10, 20, 30, 'seed']
>>> list.remove(20)
>>> list
[10, 30, 'seed']
>>> list2=list*2
>>> list2
[10, 30, 'seed', 10, 30, 'seed']
```

Note: An ordered, mutable, heterogeneous 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.

Ex:

t=(10,20,30,40)

type(t)

t[0]=100

TypeError: 'tuple' object does not support item assignment

>>> t.append("durga")

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

Ex:

r=range(10)

for i in r : print(i) 0 to 9

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

We cannot modify the values of range data type

Ex:

r[0]=100

TypeError: ‘range’ object does not support item assignment

We can create a list of values with range data type

Ex:

>>> l = list(range(10))

>>> 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
- Grow able in nature

Ex:

s={100,0,10,200,10,'seed'}

s # {0, 100, 'seed', 200, 10}

s[0] ==>TypeError: 'set' object does not support indexing

```
set is growable in nature, based on our requirement we can increase or decrease the size.
>>> s.add(60)
>>> s
{0, 100, 'seed', 200, 10, 60}
>>> s.remove(100)
>>> s
{0, 'seed', 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.

>>> s={10,20,30,40}

>>> fs=frozenset(s)

>>> type(fs)

>>> fs

frozenset({40, 10, 20, 30})

>>> for i in fs:print(i)

…

40

10

20

30

13)

>>> 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.

Exg:

d={101:'seed',102:'ravi',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.

Ex:

>>> d={101:'seed',102:'dharshi',103:'technology'}

>>> d[101]='shishir'

>>> d

{101: 'shishir', 102: 'dharshi', 103: 'technology'}

```
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:

- In general we can use bytes and bytearray data types to represent binary information like images, video files etc.
- 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.
- In Python there is no char data type. Hence we can represent char values also by using str type.

**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.

Ex:

def m1():

a=10

print(m1())

None

**Escape Characters:**

In String literals we can use esacpe characters to associate a special meaning.

>>> s="seed\nsoftware"

>>> print(s)

seed

software

>>> s="seed\tsoftware"

>>> print(s)

seed software

>>> s="This is " symbol"

File "", line 1

s="This is " symbol"

^

SyntaxError: invalid syntax

>>> s="This is \" symbol"

>>> print(s)

This is " symbol

The following are various important escape characters in Python

\n==>New Line

\t===>Horizontal tab

\r ==>Carriage Return

\b===>Back space

\f===>Form Feed

\v==>Vertical tab

\'===>Single quote

\"===>Double quote

\===>back slash symbol

**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.

MAX_VALUE=10

It is just convention but we can change the value.