You are on page 1of 12

04-data-types-in-python

February 27, 2023

1 Data Types
1.0.1 Fundamental Data Types
int = 2, float = 2.4, complex = 1+2j or a+bj, boolean = True or False, String = ‘hello’ or “hello”

1.0.2 Advanced Data Types or containers or Data Structures


List = [1,2,3] , tuple = (1,2,3) , set = {1,2,3} , dicttionary = {1:‘a’, 2:‘b’,3:‘c’}

1.1 Int - numeric value without any decimal


[1]: a = 10
print(a)

10

[2]: type(a) # used to check the type of the variable a

[2]: int

1.2 Float - numeric value with a decimal


[3]: b = 3.0
print(b)

3.0

[4]: type(b)

[4]: float

[5]: a = 3
print(3)
type(a)

[5]: int

1
1.3 Typecasting - converting from one data type to another data type
[6]: b = 5.9
print(b)

5.9

[7]: type(b)

[7]: float

[8]: int(b)

[8]: 5

[9]: int(2.88888)

[9]: 2

[10]: float(int(4.9999))

[10]: 4.0

1.4 Boolean - True / False


[11]: b1 = True
print(b1)

True

[12]: type(b1)

[12]: bool

[13]: type(False)

[13]: bool

[14]: int(True)

[14]: 1

[15]: int(False)

[15]: 0

[16]: float(True)

2
[16]: 1.0

[17]: float(False)

[17]: 0.0

1.5 Complex - a+bj


complex literals can be created by using the notation x + yj where x is the real component and y
is the imaginary component
[18]: x = 10+20.5j

[19]: print(x)

(10+20.5j)

[20]: type(x)

[20]: complex

[21]: #to get the real component or the real value


x.real

[21]: 10.0

[22]: # to get the imaginaty component or the imaginary value


x.imag

[22]: 20.5

[23]: int(x)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [23], in <cell line: 1>()
----> 1 int(x)

TypeError: can't convert complex to int

[ ]: int(2+3j)

A complex literal can not be converted to int but the int or float can be converted to complex
[ ]: complex(10)

3
1.6 String
A python string consists of a series or sequence of charecters - letters, numbers and special charecters
We can use single quotes or double quotes to represent the string
[24]: a = 'krishna'
print(a)

krishna

[25]: type(a)

[25]: str

[26]: my_string1 = "hello"


print(my_string1)

my_string2 = 'Hello'
print(my_string2)

my_string3 = "HELLO"
print(my_string3)

hello
Hello
HELLO
Multiline string can be denoted using triple quotes ”’ ”’ or ””” ”””
[27]: b = '''data science'''
print(b)

data science

[28]: b1 = '''data
science'''
print(b1)
b1

data
science

[28]: 'data\nscience'

[29]: len(b)

[29]: 12

4
[30]: v = 123456
print(v)
type(v)

123456

[30]: int

[31]: v1 = '123456'
print(v1)
type(v1)

123456

[31]: str

[32]: float(v)

[32]: 123456.0

[33]: float(v1)

[33]: 123456.0

[34]: u = 'sri@123'
print(u)

sri@123

[35]: type(u)

[35]: str

[36]: int(u)

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [36], in <cell line: 1>()
----> 1 int(u)

ValueError: invalid literal for int() with base 10: 'sri@123'

5
1.7 Length of String
[37]: string = 'krishna'
len(string)

[37]: 7

1.8 Indexing in string


• String can be indexed - often synonymously called as subsctipted
• python supports both +ve(positive) and -ve(negative) indexing
• positive(+ve) indexing means forward direction or simply forward indexing
• negative(-ve) indexing means backward direction or simply reverse indexing
• first charecter has always the index 0
• in forward indexing the indexing starts from 0 to n (n exclusive)
• in reverse indexing the indexing srarts from -1 to -n counted backwards
[38]: #print the first charecter
print(string[0])

[39]: #print charecter of index d[len(d-1)] ir d[-1]


print(string[-1])

[40]: # print charecter using negative indexing


print(string[-5])

[41]: # if we try to access the index which is out of range, then we will get an error
print(string[7])

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Input In [41], in <cell line: 2>()
1 # if we try to access the index which is out of range, then we will get␣
↪an error

----> 2 print(string[7])

IndexError: string index out of range

[42]: print(string[-9])

---------------------------------------------------------------------------

6
IndexError Traceback (most recent call last)
Input In [42], in <cell line: 1>()
----> 1 print(string[-9])

IndexError: string index out of range

[43]: # string index cannot have a decimal or if we try to access the string index␣
↪with a decimal then we will get an error

print(string[2.4])

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [43], in <cell line: 2>()
1 # string index cannot have a decimal or if we try to access the string␣
↪index with a decimal then we will get an error

----> 2 print(string[2.4])

TypeError: string indices must be integers

1.9 Slicing the String


• [start_index(inclusive) : end_index(exclusive) : step]
• step can be a +ve value or a -ve value but the default step value is +1
[51]: print(string)

krishna

[45]: print(string[2:5])# slicing with increment

ish

[47]: print(string[0:3])

kri

[49]: print(string[2:50])

ishna

[54]: print(string[5:0:-1])# slicing with decrement

nhsir

[55]: print(string[:5]) # default index 0

krish

7
[57]: print(string[2:])# default end index - len(string)

ishna

[58]: print(string[::2])

kiha

[60]: print(string[:])# slicing start to end (all)

krishna

[61]: print(string[::-1]) # print in reverse order

anhsirk

1.10 String Concatenation


• joining 2 strings into a single string is called concatenation
• The operators does this in python
• simply writing 2 string literals togather also concatenates them
[1]: 'hello' + 'world'

[1]: 'helloworld'

[3]: 'hello' + ' ' + 'world'

[3]: 'hello world'

• The * operator is used to repeat the string for a given number of times
[4]: 'AI' * 5

[4]: 'AIAIAIAIAI'

[5]: 'krishna' + 2

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [5], in <cell line: 1>()
----> 1 'krishna' + 2

TypeError: can only concatenate str (not "int") to str

• to use the + operator for strings, mandatoryly both the literals should be string only
[6]: 'krishna' + '2'

8
[6]: 'krishna2'

[7]: 'krishna' + str(3)

[7]: 'krishna3'

[9]: user = 'vikram'


lines = 100
print('congratualtions ' + user + ' you have written ' + str(lines) + ' of code!
↪')

congratualtions vikram you have written 100 of code!

[10]: print('congratualtions ' + user + ' you have written ' + lines + ' of code!')

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [10], in <cell line: 1>()
----> 1 print('congratualtions ' + user + ' you have written ' + lines + ' of␣
↪code!')

TypeError: can only concatenate str (not "int") to str

1.11 String Immutable


[1]: mystring = 'hello'
print(mystring)

hello

[2]: print(mystring[0])

[4]: mystring[0] = 's' # strings are immutable. it means the values in the string␣
↪indeces can not be replaced

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [4], in <cell line: 1>()
----> 1 mystring[0] = 's'

TypeError: 'str' object does not support item assignment

9
1.12 String Methods
• __strip() - remove spaces from the string
• rstrip() - removes spaces from the right side of the string
• lstrip() - removes spaces from the left side of the string

[15]: a = ' python '


print(a)

python

[16]: print(a.strip())

python

[8]: a.strip()

[8]: 'python'

[13]: a.lstrip()

[13]: 'python '

[14]: a.rstrip()

[14]: ' python'

[17]: a = 'gooD MorNing'

[22]: a.capitalize()# capitalize - only 1st letter of the sentence is in upper case␣
↪remaining all are in the lower case.

[22]: 'Good morning'

[23]: a.title()# title() - makes 1st letter of each word to upper case in each and␣
↪every word in the sentence.

[23]: 'Good Morning'

[24]: a.upper() # converts each and every letter in the sentence to upper case

[24]: 'GOOD MORNING'

[25]: a.lower() # converts each and every letter in the sentence to lower case

[25]: 'good morning'

[26]: a.find('o') # to find a string in a string

10
[26]: 1

[28]: a.count('o') # to find how many times a string is appeared in a main string

[28]: 3

[34]: st = 'my name is myagana'


st.split() # split with space(default)

[34]: ['my', 'name', 'is', 'myagana']

[1]: a = ['data', 'science']


''.join(a) # join 2 strings

[1]: 'datascience'

[2]: b = 'good morning'


print(b)
id(b)

good morning

[2]: 1768842124656

[4]: b = b.replace('good','bad') # replace an old string with a new string


print(b)
id(b)

bad morning

[4]: 1768842124080

[6]: c = 'sri123'
print(c.isdigit()) # to find if the string contains only numbers

print(c.isalnum()) # to find if the string contains alphabets and numbers

print(c.isalpha()) # to find if the string contains only alphabets

print(c.istitle()) # to find if the string contains the title words

print(c.isupper()) # to find if the string contains the upper case letters

print(c.islower()) # to find if the string contains the lower case letters

print(c.isspace()) # to find if the string contains spaces

print(c.endswith('s')) # to find if the string ends with letter 's'

11
print(c.startswith('s')) # to find if the string starts with the letter 's'

False
True
False
False
False
True
False
False
True

12

You might also like