# Data Types¶

The main data types in python are:

• Numbers;
• String;
• List;
• Set;
• Dictionary;

## Numbers¶

### Operators¶

In [ ]:
2 + 3

In [ ]:
2 - 3

In [ ]:
2 * 3

In [ ]:
2**3

In [ ]:
2 / 3

In [ ]:
5 // 3

In [ ]:
5 % 3


A complete list of operators is in the Python Documentation

### Number types¶

In [ ]:
2 / 3.  # float

In [ ]:
int(2 / 3.)

In [ ]:
int('1')

In [ ]:
float(1)

In [ ]:
float('1.3')

In [ ]:
long(1.300)

In [ ]:
complex(2, 3)

In [ ]:
complex('2+3j')


### Assign a variable¶

In [ ]:
one = 1

In [ ]:
one


Assign more than one variable at the same time

In [ ]:
two, three, four = 2, 3, 4

In [ ]:
print four, three

In [ ]:
a = b = c = 1

In [ ]:
a

In [ ]:
b

In [ ]:
c

In [ ]:
#working only with python3
a, *b, c = [1, 2, 3, 4, 5, 6]
a == 1
b == [2, 3, 4, 5]
c == 6

In [ ]:
complex0 = -3j  # complex

In [ ]:
complex0.imag

In [ ]:
complex0.real

In [ ]:
complex0**2


### abs, pow, round¶

In [ ]:
abs(-1.45)

In [ ]:
pow(2, 3)


To get more function we should load the math library

In [ ]:
import math
round(math.pi, ndigits=3)


### Exercise 0¶

Use python as a scientific calculator [1 minute]:

In [ ]:
x = 2 # assign a variable
y = 3
x * y

In [ ]:
math.sin(math.pi/2.) # use functions and variables from the math library
# if you import the math library with:
# from math import *
# become: sin(pi/2.)


## Boolean¶

In [ ]:
true = True
false = False
none = None
one = 1
zero = 0
a = 'a'

In [ ]:
true is True # use "is" to check that is the same object

In [ ]:
false is not True

In [ ]:
true == True

In [ ]:
one > zero # >/>=/</<=

In [ ]:
one > zero and zero > -one

In [ ]:
one < zero or zero < -one


## String¶

To define a string we must use one of ",':

In [ ]:
string ='qwertyuiopasdfghjklzxcvbnm'


In python we can see a string as an array of characters, the first element of a list index == 0 (Python as C and oder languages start from 0).

In [ ]:
string[0]  # get the first element of the string

In [ ]:
len(string)  # get the lenght of the string

In [ ]:
string[25]  # get the last element of the string

In [ ]:
string[-1]  # get the last


Slicing in python, we use ":" to divide the start, finish and the step.

In [ ]:
string[0:6] # start=0, stop=6

In [ ]:
string[::3] # step=3


### Exercise 1¶

Reverse the string using slice [1 minute]

In [ ]:



Solution:

In [ ]:



It is possible to specify if the encoding system of the string is unicode starting the string definition with: 'u'

In [ ]:
unicodestr = u'àèéìçòù'

In [ ]:
unicodestr[:3]

In [ ]:
print unicodestr[:3]


String are not a modifiable object

In [ ]:
numb = '0123-5678'

In [ ]:
numb[4]


If we try to modify the fourth character python raise an error, because this operation are not allowed by the string class.

In [ ]:
numb[4] = 4


Mathematical operation with the strings, only summation and multiplication are allowed.

In [ ]:
'a'+'b'+'c'

In [ ]:
'abc'-'c'

In [ ]:
'a'*4


### Exercise 2¶

Substitute the character '-' with '4' using the slice and the mathematical properties of the string class. [2 minutes]

In [ ]:



Possible solution

In [ ]:



To define a multirow string in python we simple need to add somewhere the character "\n" inside the string

In [ ]:
multirow = 'Things that I like in python:\n    - syntax;\n    - power.\n'
print multirow

In [ ]:
multirow = """Things that I like in python:
- syntax;
- power.
"""
print multirow


String as objects: some methods of the string class.

In [ ]:
findstr = "find something inside"

In [ ]:
findstr.find('s')

In [ ]:
findstr[9:]

In [ ]:
findstr[9:].find('s')

In [ ]:
print(multirow.replace('syntax', "it's nice"))

In [ ]:
stripstr = '   some spaces    '

In [ ]:
stripstr.strip() # try the effect of: lstrip, rstrip

In [ ]:
splitstr = "split a long phrase, with a lot of words!"

In [ ]:
splitstr.split()  # specify with character should be use to split the string, the defaul is ' '


### Exercise 3¶

Play with the string using some other methods like: upper, capitalize, lower, isdigit, islower, etc. [2 minutes]

In [ ]:


In [ ]:
character = 'A strAngE strIng'
character.lower()

In [ ]:
numbers = '1234'
numbers.isdigit()


String formatting with python as in C

In [ ]:
'python is %s!!!' % 'beautiful'

In [ ]:
import math
'number int: %05d, float: %f' % (15, math.pi)

In [ ]:
'number int: %d, float: %05.2f' % (15, math.pi*100)

In [ ]:
'list: %r' % [1,2,3,4]


String formatting using the "format" method of the string class.

In [ ]:
'SELECT {cols} FROM {table}'.format(cols='cat, name', table='streets')

In [ ]:
'SELECT {} FROM {}'.format('cat, name','streets')


### Exercise 4¶

Using the following variables:

In [ ]:


In [ ]:
integer = -12345
double = 3.141592653589793
word = 'python'

Get the following strings [3 minutes]: "Still missing: -12345 €" "the pigreco value is around: 3.14159" " python "
In [ ]:


In [ ]:


In [ ]:



## List¶

In [ ]:
list_one = ["a", "b", "c", [1,2,3], "d"]

In [ ]:
list_one

In [ ]:
list_one[1]

In [ ]:
list_one[0]


If we use a negative index we start from the last

In [ ]:
list_one[-2]


Using the ":" we separate the index of the first element, the last, and the step [first:last:step], these operation is called slicing.

In [ ]:
list_one[1:4]

In [ ]:
list_one[::2]

In [ ]:
list_one[::-1]


The list have some usefull methods, like:

In [ ]:
list_one.append('a')

In [ ]:
list_one.count('a')

In [ ]:
len(list_one)

In [ ]:
list_one.pop(-1)

In [ ]:
list_one.sort()

In [ ]:
list_one

In [ ]:
list_one.index('b')

In [ ]:
list_one.extend(['e','f','g','h'])

In [ ]:
list_one

In [ ]:
list_one[0][0:0]=[0]
list_one

In [ ]:
list_one.insert(1, [4,5,6])
list_one

In [ ]:
list_one[-3:]=[]
list_one

In [ ]:
list_one.remove('e')
list_one

In [ ]:
'a' in list_one


## Tuple¶

As a list but is unmodifiable

In [ ]:
tuple_one = (1,2,3,':-)')

In [ ]:
tuple_one.index(2)

In [ ]:
tuple_one.count(':-)')

In [ ]:
2 in tuple_one

In [ ]:
tuple_one[0]

In [ ]:
tuple_one[0] = 10


## Set¶

Another data types that is available in python is "set".

In [ ]:
gis = set(['arcgis', 'mapinfo', 'qgis', 'grass', 'udig'])
opensource = set(['qgis', 'grass', 'udig'])
usingpython = set(['qgis', 'grass', 'arcgis'])

In [ ]:
gis - opensource

In [ ]:
opensource & usingpython  # and

In [ ]:
opensource ^ usingpython  # or


## Dictionary¶

The last data type used in python that we see today is the dictionary, lets define a dictionary with the address number.

In [ ]:
contact = {'pietro': 333123808, 'jonh': 123123123}

In [ ]:
contact['pietro']

In [ ]:
contact['pietro'] = {'cell': 333123808, 'tel': 04545454}

In [ ]:
contact['pietro']['cell']


### Exercise 5¶

Some dictionary methods: keys, values, items [1 minute]

In [ ]:


In [ ]:
contact.keys()


## Verify the type of an object¶

In [ ]:



To verify the type of an object we have some usefull function like:

• type
• isinstance
In [ ]:
type(contact)

In [ ]:
type(1)

In [ ]:
isinstance(contact, dict)


### Exercise 6¶

Verify the type of the other objects that we have define untill now. [2 minutes]

In [ ]: