You are on page 1of 27

Python Programming – Data

Types
Networking for Software Developers
Narendra Pershad
Agenda

• Recognize the different types


• None, Numerics, Sequence, Sets, Mappings

• When to use them

• How to use them


• What operations are possible
• How to determine types at runtime
• How to print them

• Converting between them

• It is expected that you would have prior knowledge of C# primitive type and C# collections so you may start
using the python types immediately.
Python built-in types
• None:
• The Null object
• Numerics:
• Integral
• int, bool
• float, complex
• Sequences:
• Immutable
• Strings, Tuples and Bytes
• Mutable
• Lists, Byte Arrays
• Set types:
• Set (mutable) and Frozen sets (immutable)
• Mappings:
• Dictionary

• All categories are a part of the python language i.e. you don’t need separate libraries to use them
• P.S. to know more about any object type help(object) or dir(object)
Numeric
Numbers are immutable, this means that values in memory are not mutated, another spot is chosen with
the new value

There are three types of numbers:


• Int have unlimited precision
• int literals
7, 0b100, 0o27, 0xf

• Float literals
3.14, 10., .001, 1e100, 3.14e-10

• Complex literals
3.14j, 10.j, 10j, .001j, 1e100j, 3.14e-10j
Conversions
>>> int(3.14)
3

>>> float(5)
5.0

>>> complex(3)
(3+0j)

>>> complex(1, 2)
(1+2j)
Bool
• This is a numeric sub-type
• There are only two literal bool values:
• True
• False

• Unlike C#, however any python object can be tested for truth value. The following values will be considered False:
• None

• False

• Zero numeric type: 0, 0l, 0.0, 0j

• Any empty sequence: '', {}, []

• All other values are considered True


>>> bool('true') #True

>>> bool('False') #True

>>> bool('lkjlk') #True

>>> bool('') #False

>>> bool(89) #True

>>> bool(0) #False

>>> bool([]) #False

>>> bool([0]) #True

>>> bool({}) #False


Sequences
• The six sequences in python shares some common operations:

• All the entries do not have to be the same type


• Strings (Binary and Unicode)
• Tuples -> ()
• Lists -> []
• stack, queue will not be covered in this course

• Reminder
• To see all the variables in scope, use the dir() command
• To get type information on a variable, use the type(var) command
• To facilitate the introspection of a variable, use the dir(var) command
• To get help on a topic, use the help(topic)
String
• Strings are text delimited by a matching pair of single, double or triple quotes

• In this course, we will use a single quote for strings with a few exception
>>> a = 'Hello world'
>>> a
'Hello world'

>>> a = "Narendra's toys"


>>> a
"Narendra's toys"
Multi-lined strings
>>> a = 'First line ‘ \
... 'second line ‘ \
... 'third line'
>>> a
'First line second line third line’

>>> a = '''First line


... second line
... third line'''
>>> a
'First line \nsecond line \nthird line'
Byte strings
>>> a = b'First line'
>>> a
b'First line'

>>> type(a)
<class 'bytes'>

>>> list(a) # byte string to list


[70, 105, 114, 115, 116, 32, 108, 105, 110, 101]

>>> list('First line’) # normal string to list


['F', 'i', 'r', 's', 't', ' ', 'l', 'i', 'n', 'e']
Unicode strings
>>> a = '\u00c4\u00e8' #four hex digits for a single character
>>> a
'Äè'

>>> a = '\U000000c4\U000000e8' #eight hex digits for a single character


>>> a
'Äè'

>>> ord(a[0])
196

>>> chr(196)
'Ä'
>>> a = 'the quick brown fox jumps over the lazy dog'
>>> a.split()
['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog’]

>>> a.upper() #there is also a lower


'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG’

>>> a.capitalize()
'The quick brown fox jumps over the lazy dog’

>>> a.title()
'The Quick Brown Fox Jumps Over The Lazy Dog’

>>> a.replace('o', 'O')


'the quick brOwn fOx jumps Over the lazy dOg’

>>> a.replace('o', 'O').swapcase()


'THE QUICK BRoWN FoX JUMPS oVER THE LAZY DoG’

>>> a.find('dog')
40
Tuples
• A sequence of immutable python objects.
• This means that it may not be changed after assignment

• The items does not necessary have to be the same type

tup1 = ( )

tup2 = ( 'programming', 'english', 'mathematics', 2018, 3.14 )

tup3 = ( 1, 2, 3, 4, 5, 3, 2, 1 )

tup4 = ( 'narendra', 'pershad' )


List
• A sequence of mutable python objects
lst1 = [ ]

lst2 = ['programming', 'english', 'mathematics', 2018, 3.14]

lst3 = [1, 2, 3, 4, 5, 3, 2, 1]

lst4 = ['narendra', 'pershad']

• An index can be negative… i.e. that starts from the end


Lst2[-1] # 3.14

Lst2[-3] # 'mathematics'
Common methods of List
• append()
• clear()
• copy()
• count()
• extend()
• index()
• insert()
• pop()
• remove()
• sort()
• reverse()
Traversing a sequence
• There are two way of traversing a sequence

for item in sequence:


print(item)

for i in range(len(sequence)):
print(sequence[i]) # does not work with set, dictionary
append(item)
• Adds item to the end of the sequence (not available for sets or tuples)

>>> a = [2, 4, 6]
>>> a
[2, 4, 6]

>>> a.append(8)
>>> a
[2, 4, 6, 8]

>>> a.append([10]) #append a list


>>> a
[2, 4, 6, 8, [10]]

>>> a.append((12, 13 , 14)) #append a tuple


>>> a.append({16}) #append a set
>>> a
[2, 4, 6, 8, [10], (12, 13, 14), {16}]
clear() and copy() count()
Returns a copy of the list
>>> b = a.copy() #b is now a duplicate of a
>>> b
[2, 4, 6, 8, [10], (12, 13, 14), {16}]

>>> len(a) #the number of items in a


7

>>> a.count([10]) #the number of occurrence of [10]


7

Removes all the items from a sequence


>>> b.clear() #b is now empty
>>> b
[]

• extend()
Common method of sequences
• index()

• Insert(«index», «item»)
• Inserts the item at the specified position

• pop([position])
• Removes and return the item at position from sequence

• remove(«item»)
• Removes the specified item from the list

• sort()

• reverse()
• Returns a reversed version of this sequence.
• Note the original sequence is changed
append()
• Adds a new entry to the end
clear()
• Removes all the entries of this sequence
Set
• A sequence of unique immutable python objects
• Sets, list or dict cannot be in a set
• Mimics a Mathematical set

set1 = { }
set2 = { 'programming', 'english', 'mathematics', 2018, 3.14 }
set3 = { 1, 2, 3, 4, 5, 3, 2, 1 } # only unique items will be in the resulting set
set4 = { 'Centennial', 'College' }

• Set does not support indexing


Dictionary
• A sequence of key-value pairs.

• Each key must be unique and immutable such as strings, numbers, or tuples. A list may not be a key

• There is no restriction on the value, it may be any python object

dict1 = {'Ilia' : 'red', 'Narendra' : 'green', 'Arben' : , 'Hao' : 'blue' }

• Dictionary does not support positional indexing


Some operations on dictionary
• Consider the following dictionary
Python3 reserved words
False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass

break except in raise


Summary

• Python has a much richer set of built-in types than most languages.

• There are also lots of functions that interacts or support these types.

• You can query the type of any variable via the dir() function.

• You can also get more information via the help() function

You might also like