You are on page 1of 23

Chapter 2

Basic Data Types in Python

Truong Phong Tuyen, PhD


Department of Electronics and Telecommunication Engineering
College of Engineering Technology
Can Tho University
Email: tptuyen@ctu.edu.vn
Python Data Types

● Built-in python data types


○ Python Data Type – Numeric
○ Python Data Type – String
○ Python Data Type – List
○ Python Data Type – Tuple
○ Dictionary

2
Python Data Type – NUMERIC (1)

● Numeric data type is used to hold numeric values


○ int - holds signed integers of non-limited length
○ long - holds long integers (exists in Python 2.x,
deprecated in Python 3.x).
○ float - holds floating precision numbers and it’s
accurate upto 15 decimal places.
○ complex - holds complex numbers.

3
Python Data Type – NUMERIC (2)
● Not to declare datatype; just assign values in a variable
● Use type() to see what type of numerical value is it holding
>>> a = 10
>>> type(a)
<class 'int'>
>>> b = 1.234
>>> type(b)
<class 'float'>
>>> c = 5 + 6j
>>> type(c)
<class 'complex'>
>>> d = 1.123456789123456
4
Python Data Type – STRING (1)

● The string is a sequence of characters.


● Python supports Unicode characters.
● Strings are represented by either single or double quotes.

5
Python Data Type – STRING (2)

>>> a = 'Hello World!' >>> a ='Hello\nTuyen'


>>> b = "Hello World!" >>> print (a)
>>> a == b Hello
True Tuyen
>>> a = "Tuyen's lecture" >>> b = """One line,
>>> print(a) ... another line,
Tuyen's lecture ... and some ..."""
>>> a = "One line.\nAnother line." >>> print(b)
>>> print(a) One line,
One line. another line,
Another line. and some ...

6
Python Data Type – STRING (3)
>>> a = "79"
>>> type(a)
<class 'str'>
>>> b = int(a)
>>> type(b)
<class 'int'>
>>> f = float('1.5e-3')
>>> f
0.0015
>>> print(f)
0.0015
>>> eval('79-39')
40
7
Python Data Type – STRING (4)
>>> a = "Part 1" >>> s[2:-1]
>>> b = "and part 2" 'cd'
>>> a + ' ' + b >>> s
'Part 1 and part 2' 'abcde'
>>> s = a * 2 >>> s[:3]
>>> print(s) 'abc'
Part 1Part 1 >>> s[2:5]
>>> s="abcde" 'cde'
>>> s[0] >>> s[:3]
'a' 'abc'
>>> s[1:4] >>> s[2:]
'bcd' 'cde'
>>> s[-1] >>> s[1:4:2]
'e' 'bd' 8
Python Data Type – STRING (5)
>>> print(s)
abcde
>>> len(s)
5
>>> 'p' in s
False
>>> 'c' in s
True
>>> 'cd' in s
True
>>> s[1] = 'B'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> s = 'A' + s[1:]
>>> print(s)
Abcde 9
Python Data Type – STRING (6)
>>> s = 'a string, with stuff'
>>> s.count('st')
2
>>> s.find('stu')
15
>>> s.split(' ')
['a', 'string,', 'with', 'stuff']
>>> three = '3'
>>> three.isdigit()
True
>>> supper = s.upper()
>>> supper
'A STRING, WITH STUFF'
>>> s.rjust(30)
' a string, with stuff'
>>> "newlines\n\n\n".strip()
'newlines' 10
Python Data Type – LIST (1)

● Similar to an array in many other programming


languages but more flexible.
● An ordered sequence of some data written using
square brackets([]) and commas(,).
○ Lists are ordered lists
○ Can contain arbitrary objects
○ List elements can be accessed by index
○ Lists can be nested
○ Lists are mutable lists are dynamic
11
Python Data Type – LIST (2)
>>> r = [1, 2.0, 3, 5]
>>> r
[1, 2.0, 3, 5]
>>> type(r)
<class 'list'>
>>> r[1]
2.0
>>> r[-1]
5
>>> r[1:3]
[2.0, 3]
>>> w = r + [9, 6]
>>> w
[1, 2.0, 3, 5, 9, 6]
>>> t = [1.0] * 10
>>> t
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] 12
Python Data Type – LIST (3)
>>> r = [1, 2.0, 3, 5] >>> r[1:3] = []
>>> r[3] = 'world' >>> r
>>> r [1, 8, 'world']
[1, 2.0, 3, 'world'] >>> len(r)
>>> r[0] = [7, 4] 3
>>> r >>> 8 in r
[[7, 4], 2.0, 3, 'world'] True
>>> r[0:3] = [1, 2, 4, 8] >>> r.index(8)
>>> r 1
[1, 2, 4, 8, 'world']

13
Python Data Type – LIST (4)
>>> r = [1, 2.0, 3, 5]
>>> r.append('thing')
>>> r
[1, 2.0, 3, 5, 'thing']
>>> r.append(['another','list'])
>>> r
[1, 2.0, 3, 5, 'thing', ['another', 'list']]
>>> r = [1, 2.0, 3, 5]
>>> r.extend(['item', 'another'])
>>> r
[1, 2.0, 3, 5, 'item', 'another']
>>> k = r.pop()
>>> k
'another'
>>> r
[1, 2.0, 3, 5, 'item']
14
Python Data Type – LIST (5)
>>> r = [2, 5, -1, 0, 20]
>>> r.sort()
>>> r
[-1, 0, 2, 5, 20]
>>> w = ['apa', '1', '2', '1234']
>>> w.sort()
>>> w
['1', '1234', '2', 'apa']
>>> w.reverse()
>>> w
['apa', '2', '1234', '1']
>>> v = w[:]
>>> v.reverse()
>>> v
['1', '1234', '2', 'apa']
>>> w
['apa', '2', '1234', '1'] 15
Python Data Type – LIST (6)
>>> s = 'biovitrum'
>>> w = list(s)
>>> w
['b', 'i', 'o', 'v', 'i', 't', 'r', 'u', 'm']
>>> w.reverse()
>>> w
['m', 'u', 'r', 't', 'i', 'v', 'o', 'i', 'b']
>>> r =''.join(w)
>>> r
'murtivoib'
>>> d = '-'.join(w)
>>> d
'm-u-r-t-i-v-o-i-b'
>>> s = 'a few words'
>>> w = s.split()
>>> w
['a', 'few', 'words'] 16
Python Data Type – TUPLES (1)

● Tuples are identical to lists in all respects, except for


the following properties:
○ Tuples are defined by enclosing the elements in
parentheses , (), instead of square brackets, [].
○ Tuples are immutable.

17
Python Data Type – TUPLES (2)
>>> t = (1, 3, 2)
>>> t[1]
3
>>> (a, b, c) = t
>>> a
1
>>> a, b, c
(1, 3, 2)
>>> a, b = b, a
>>> a, b
(3, 1)
>>> r = list(t)
>>> r
[1, 3, 2]
>>> tuple(r)
(1, 3, 2)
18
Python Data Type – DICTIONARY (1)

● Dictionary: Another composite data type which is similar to a List


● Dictionaries and lists share the following characteristics:
○ Both are mutable.
○ Both are dynamic. They can grow and shrink as needed.
○ Both can be nested. A list can contain another list. A dictionary can
contain another dictionary. A dictionary can also contain a list, and
vice versa.
● Dictionaries differ from lists primarily in how elements are accessed:
○ List elements are accessed by their position in the list, via indexing.
○ Dictionary elements are accessed via keys.

19
Python Data Type – DICTIONARY (2)
>>> h = {'key':12,'nyckel':'word'}
>>> h['key']
12
>>> 'nyckel' in h
True
>>> h['Per'] = 'Kraulis'
>>> h
{'key': 12, 'nyckel': 'word', 'Per': 'Kraulis'}
>>> h['nyckel'] = 'Kraulis'
>>> h
{'key': 12, 'nyckel': 'Kraulis', 'Per': 'Kraulis'}
>>> del h['nyckel']
>>> h
{'key': 12, 'Per': 'Kraulis'} 20
Python Data Type – DICTIONARY (3)
>>> h = {'key':12,'nyckel':'word'}
>>> 'Per' in h
False
>>> h['Per']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Per'
>>> h.get('Per','unknown')
'unknown'
>>> h.get('key','unknown')
12
>>> h.keys()
dict_keys(['key', 'nyckel'])
>>> h.values()
dict_values([12, 'word'])
>>> len(h)
2 21
Python Data Type – DICTIONARY (4)
>>> h = {'key':12,'nyckel':'word'}
>>> g = h.copy()
>>> del h['key']
>>> h
{'nyckel': 'word'}
>>> g
{'key': 12, 'nyckel': 'word'}
>>> h['Per'] = 'Johansson'
>>> h
{'nyckel': 'word', 'Per': 'Johansson'}
>>> h.update(g)
>>> h
{'nyckel': 'word', 'Per': 'Johansson', 'key': 12}
22
Questions and Answers

23

You might also like