The main data types in python are:
2 + 3
2 - 3
2 * 3
2**3
2 / 3
5 // 3
5 % 3
A complete list of operators is in the Python Documentation
2 / 3. # float
int(2 / 3.)
int('1')
float(1)
float('1.3')
long(1.300)
complex(2, 3)
complex('2+3j')
one = 1
one
Assign more than one variable at the same time
two, three, four = 2, 3, 4
print four, three
a = b = c = 1
a
b
c
#working only with python3
a, *b, c = [1, 2, 3, 4, 5, 6]
a == 1
b == [2, 3, 4, 5]
c == 6
complex0 = -3j # complex
complex0.imag
complex0.real
complex0**2
abs(-1.45)
pow(2, 3)
To get more function we should load the math library
import math
round(math.pi, ndigits=3)
Use python as a scientific calculator [1 minute]:
x = 2 # assign a variable
y = 3
x * y
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.)
true = True
false = False
none = None
one = 1
zero = 0
a = 'a'
true is True # use "is" to check that is the same object
false is not True
true == True
one > zero # >/>=/</<=
one > zero and zero > -one
one < zero or zero < -one
To define a string we must use one of ",':
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).
string[0] # get the first element of the string
len(string) # get the lenght of the string
string[25] # get the last element of the string
string[-1] # get the last
Slicing in python, we use ":" to divide the start, finish and the step.
string[0:6] # start=0, stop=6
string[::3] # step=3
Reverse the string using slice [1 minute]
Solution:
It is possible to specify if the encoding system of the string is unicode starting the string definition with: 'u'
unicodestr = u'àèéìçòù'
unicodestr[:3]
print unicodestr[:3]
String are not a modifiable object
numb = '0123-5678'
numb[4]
If we try to modify the fourth character python raise an error, because this operation are not allowed by the string class.
numb[4] = 4
Mathematical operation with the strings, only summation and multiplication are allowed.
'a'+'b'+'c'
'abc'-'c'
'a'*4
Substitute the character '-' with '4' using the slice and the mathematical properties of the string class. [2 minutes]
Possible solution
To define a multirow string in python we simple need to add somewhere the character "\n" inside the string
multirow = 'Things that I like in python:\n - syntax;\n - power.\n'
print multirow
multirow = """Things that I like in python:
- syntax;
- power.
"""
print multirow
String as objects: some methods of the string class.
findstr = "find something inside"
findstr.find('s')
findstr[9:]
findstr[9:].find('s')
print(multirow.replace('syntax', "it's nice"))
stripstr = ' some spaces '
stripstr.strip() # try the effect of: lstrip, rstrip
splitstr = "split a long phrase, with a lot of words!"
splitstr.split() # specify with character should be use to split the string, the defaul is ' '
Play with the string using some other methods like: upper, capitalize, lower, isdigit, islower, etc. [2 minutes]
character = 'A strAngE strIng'
character.lower()
numbers = '1234'
numbers.isdigit()
String formatting with python as in C
'python is %s!!!' % 'beautiful'
import math
'number int: %05d, float: %f' % (15, math.pi)
'number int: %d, float: %05.2f' % (15, math.pi*100)
'list: %r' % [1,2,3,4]
String formatting using the "format" method of the string class.
'SELECT {cols} FROM {table}'.format(cols='cat, name', table='streets')
'SELECT {} FROM {}'.format('cat, name','streets')
Using the following variables:
integer = -12345
double = 3.141592653589793
word = 'python'
list_one = ["a", "b", "c", [1,2,3], "d"]
list_one
list_one[1]
list_one[0]
If we use a negative index we start from the last
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.
list_one[1:4]
list_one[::2]
list_one[::-1]
The list have some usefull methods, like:
list_one.append('a')
list_one.count('a')
len(list_one)
list_one.pop(-1)
list_one.sort()
list_one
list_one.index('b')
list_one.extend(['e','f','g','h'])
list_one
list_one[0][0:0]=[0]
list_one
list_one.insert(1, [4,5,6])
list_one
list_one[-3:]=[]
list_one
list_one.remove('e')
list_one
'a' in list_one
As a list but is unmodifiable
tuple_one = (1,2,3,':-)')
tuple_one.index(2)
tuple_one.count(':-)')
2 in tuple_one
tuple_one[0]
tuple_one[0] = 10
Another data types that is available in python is "set".
gis = set(['arcgis', 'mapinfo', 'qgis', 'grass', 'udig'])
opensource = set(['qgis', 'grass', 'udig'])
usingpython = set(['qgis', 'grass', 'arcgis'])
gis - opensource
opensource & usingpython # and
opensource ^ usingpython # or
The last data type used in python that we see today is the dictionary, lets define a dictionary with the address number.
contact = {'pietro': 333123808, 'jonh': 123123123}
contact['pietro']
contact['pietro'] = {'cell': 333123808, 'tel': 04545454}
contact['pietro']['cell']
Some dictionary methods: keys, values, items [1 minute]
contact.keys()
Add your contact into the the contact dictionary.
To verify the type of an object we have some usefull function like:
type(contact)
type(1)
isinstance(contact, dict)
Verify the type of the other objects that we have define untill now. [2 minutes]