Examples of data types in Python Programming

0

Data types in Python

Every value in Python has a datatype

data types are actually classes and variables are instance (object) of these classes .

 

All Contributions

Conversion between data types :

We can convert between different data types by using different type conversion functions like int(), float(), str()

Example :

>>> float(5)
5.0

Another example :

>>> int(10.6)
10
>>> int(-10.6)
-10

Another example :

>>> float('2.5')
2.5
>>> str(25)
'25'
>>> int('1p')
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1p'

We can even convert one sequence to another :

>>> set([1,2,3])
{1, 2, 3}
>>> tuple({5,6,7})
(5, 6, 7)
>>> list('hello')
['h', 'e', 'l', 'l', 'o']

To convert to dictionary, each element must be a pair:

>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
{3: 26, 4: 44}

 

Python Dictionary :

Dictionary is an unordered collection of key-value pairs.

Example :

>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>

Another example :

d = {1:'value','key':2}
print(type(d))
print("d[1] = ", d[1])
print("d['key'] = ", d['key'])
# Generates error
print("d[2] = ", d[2])

Python Strings :

String is sequence of Unicode characters

Example :

s = "This is a string"
print(s)
s = '''A multiline
string'''
print(s)

Another example :

s = 'Hello world!'
# s[4] = 'o'
print("s[4] = ", s[4])
# s[6:11] = 'world'
print("s[6:11] = ", s[6:11])
# Generates error
# Strings are immutable in Python
s[5] ='d'

Python Tuple :

Tuple is an ordered sequence of items same as a list.

Example :

t = (5,'program', 1+3j)
# t[1] = 'program'
print("t[1] = ", t[1])
# t[0:3] = (5, 'program', (1+3j))
print("t[0:3] = ", t[0:3])
# Generates error
# Tuples are immutable
t[0] = 10

Python List :

List is an ordered sequence of items. It is one of the most used datatype in Python and is very flexible

Example :

a = [5,10,15,20,25,30,35,40]
# a[2] = 15
print("a[2] = ", a[2])
# a[0:3] = [5, 10, 15]
print("a[0:3] = ", a[0:3])
# a[5:] = [30, 35, 40]
print("a[5:] = ", a[5:])

total contributions (6)

New to examplegeek.com?

Join us