In [5]:
for x in range(10):
    print("10" + 3)
    pass

In [6]:
bool("")


Out[6]:
False

In [7]:
choice = ""
bool(choice)


Out[7]:
False

In [9]:
choice = "N"
bool(choice[0] == "N")


Out[9]:
True

In [11]:
choice = ""
bool(choice is False)


Out[11]:
False

In [12]:
bool(choice == False)


Out[12]:
False

In [13]:
l2 = [1,2,3,10,100,200,4, 8]
l3 = [ x*2 for x in l2]

In [14]:
l3


Out[14]:
[2, 4, 6, 20, 200, 400, 8, 16]

In [25]:
def rdouble(x):
    return x*2

l3_map = map(rdouble, l2)
l3_map


Out[25]:
[2, 4, 6, 20, 200, 400, 8, 16]

In [20]:
for i in range(10):
    pass
print("Ciao {}".format(i))


Ciao 9

In [22]:
int(3*2)


Out[22]:
6

In [23]:
map(int(3*2), l2)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-23-caed4a574066> in <module>()
----> 1 map(int(3*2), l2)

TypeError: 'int' object is not callable

In [24]:
int(3*2)


Out[24]:
6

In [26]:
x


Out[26]:
8

In [27]:
# map(rdouble, l2)
for z in l2:
    rdouble(z)
    
# map(int(y*2), l2)

for z in l2:
    int(y*2)(z)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-27-e931d9e08ae7> in <module>()
      6 
      7 for z in l2:
----> 8     int(y*2)(z)
      9 
     10 # Per fare qualcosa di simile a map(y*2, l2)

NameError: name 'y' is not defined

In [28]:
# Per fare qualcosa di simile a map(y*2, l2)
# Come facciamo? Utilizzare lambda

# def rdouble(x):
#    return x*2
# In notazione lambda è 
# rdouble = lambda x: x*2

map(lambda x: x*2, l2)


Out[28]:
[2, 4, 6, 20, 200, 400, 8, 16]

In [29]:
rdouble = lambda x: x*2
rdouble(10)


Out[29]:
20

In [30]:
dict(name="Luca")


Out[30]:
{'name': 'Luca'}

In [34]:
raw_input("Vuoi continuare [Y/n]? ").upper() != "N"


Vuoi continuare [Y/n]? asdfoiausodfisaufoisa
Out[34]:
True

In [ ]:
break
while True:
        print("(RI)COMINCIO")
        while True:
            a = raw_input("Vuoi continuare [Y/n]? ").upper()
            if a in ["Y", "N"]:
                break

        if a == "N":
            print("esco")
            break

In [9]:
# Scoping delle variabili
# http://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules
# http://www.saltycrane.com/blog/2008/01/python-variable-scope-notes/

print("ciao")

def funca():
    y = 0
    while True:
        while True:
            x = 3
            if y < 2:
                y += 1
            else:
                break
        if y >= 2:
            break
    print(x, y)
    
funca()
print(y)


ciao
(3, 2)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-9-ed2710cfff47> in <module>()
     15 
     16 funca()
---> 17 print(y)

NameError: name 'y' is not defined

In [10]:
len(xrange(10))


Out[10]:
10

In [23]:
import json
def get_json(data):
    return json.dumps(data, indent=2)

In [25]:
d = {"name": 'Lu""ca', "city": "Fabriano"}
print(get_json([d]))


[
  {
    "city": "Fabriano", 
    "name": "Lu\"\"ca"
  }
]

In [21]:
str(d)


Out[21]:
'{\'city\': \'Fabriano\', \'name\': \'Lu""ca\'}'

In [17]:
for x in PEOPLE:
    print("{name},{city}".format(**x))


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-17-3b78ab98ffed> in <module>()
----> 1 for x in PEOPLE:
      2     print("{name},{city}".format(**x))

NameError: name 'PEOPLE' is not defined

Esercizi

Scrivere una funzione che modifica i dizionari delle persone aggiungendo una chiave "annual" con lo stipendio annuale

Scriverne un'altra che elenchi le persone per città


In [28]:
s.upper(), s.index("a"), s.startswith("B")


Out[28]:
('CIAO', 2, False)

In [29]:
s.__len__()


Out[29]:
4

In [30]:
len(s)


Out[30]:
4

In [31]:
len(s) -> s.__len__()
a + b -> a.__add__(b)


  File "<ipython-input-31-00b077b45f12>", line 1
    len(s) -> s.__len__()
            ^
SyntaxError: invalid syntax

In [35]:
class Greeter(object):

    def __init__(self, name):
        self.name = name
        
    def hello(self):
        print("Hello {0.name}".format(self))
        
luca = Greeter("Luca")
luca.hello()
simone = Greeter("Simone")
simone.hello()


Hello Luca
Hello Simone

In [36]:
def compute_annual_single(p):
    p["annual"] = ...
    
def compute_annual_all(people):
    for p in people:
        compute_annual_single(p)


  File "<ipython-input-36-3f89aa622536>", line 2
    p["annual"] = ...
                  ^
SyntaxError: invalid syntax

In [37]:
import copy
d = {"name": "Luca"}
copy_d = copy.copy(d)
copy_d = copy.deepcopy(d)

In [53]:
import json
import csv

people_fname = r"c:\Users\gigi\lessons-python4beginners\src\gestionale\people_fixture.json"
with open(people_fname, "rb") as fpeople:
    PEOPLE = json.load(fpeople)
outfname = r"c:\Users\gigi\a.txt"

class DebugExporter(object):
    def do_export(self, f, rows):
        for row in rows:
            print("{}\n".format(row))
            
class Exporter(object):
    def do_export(self, f, rows):
        for row in rows:
            f.write("{}\n".format(row))

class JsonExporter(object):
    def do_export(self, f, rows):
        json.dump(rows, f, indent=2)


class CsvExporter(object):
    def do_export(self, f, rows):
        
        fieldnames = rows[0].keys()
        writer = csv.DictWriter(
            f, fieldnames = fieldnames, delimiter = ";")
        writer.writeheader()
        
        for row in rows:
            writer.writerow(row)

In [56]:
def apply_exportation(xp, fname, data):
    with open(fname, "wb") as f:
        xp.do_export(f, rows=data)

In [58]:
xp = JsonExporter()
apply_exportation(xp, outfname, data=PEOPLE)

xpcsv = CsvExporter()
csvfname = outfname.replace(".txt",".csv")
apply_exportation(xpcsv, csvfname, data=PEOPLE)

In [ ]: