Added the EVI 2016 python docs.
This commit is contained in:
BIN
EVI - 2016/EVI - 33/EVI_33.pdf
Normal file
BIN
EVI - 2016/EVI - 33/EVI_33.pdf
Normal file
Binary file not shown.
132
EVI - 2016/EVI - 33/Examples/basics.py
Normal file
132
EVI - 2016/EVI - 33/Examples/basics.py
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
#####################
|
||||||
|
# Atomic data types #
|
||||||
|
#####################
|
||||||
|
|
||||||
|
a = 89 # Integer
|
||||||
|
b = 0.5 # Float
|
||||||
|
c = 9 + 0.4j # Complex
|
||||||
|
d = True # Boolean
|
||||||
|
e = None # Nonetype
|
||||||
|
|
||||||
|
########################
|
||||||
|
# Composite data types #
|
||||||
|
########################
|
||||||
|
|
||||||
|
f = [1, '2', 3] # List
|
||||||
|
g = (1, '2', 3) # Tuple
|
||||||
|
h = {1: 'one', # Dict
|
||||||
|
'two': 2,
|
||||||
|
3: 'Three'}
|
||||||
|
i = set([1, 2, 3]) # Set
|
||||||
|
j = frozenset(f) # Frozen set
|
||||||
|
|
||||||
|
######################
|
||||||
|
# Control structures #
|
||||||
|
######################
|
||||||
|
|
||||||
|
# If
|
||||||
|
if 1 < 2:
|
||||||
|
print("It's true!")
|
||||||
|
elif 2 < 1:
|
||||||
|
print("It's false!")
|
||||||
|
else:
|
||||||
|
print("It's neither!")
|
||||||
|
|
||||||
|
# For
|
||||||
|
for i in f:
|
||||||
|
print(i)
|
||||||
|
|
||||||
|
# While
|
||||||
|
while a > 80:
|
||||||
|
print(a)
|
||||||
|
a -= 1
|
||||||
|
|
||||||
|
########################
|
||||||
|
# Function definitions #
|
||||||
|
########################
|
||||||
|
|
||||||
|
# No arguments
|
||||||
|
|
||||||
|
def fun():
|
||||||
|
return 89
|
||||||
|
|
||||||
|
fun()
|
||||||
|
|
||||||
|
# Functions without a return statement return None
|
||||||
|
|
||||||
|
def non():
|
||||||
|
pass
|
||||||
|
|
||||||
|
print(non())
|
||||||
|
|
||||||
|
# Positional arguments
|
||||||
|
|
||||||
|
def sum(a, b):
|
||||||
|
return a + b
|
||||||
|
|
||||||
|
print(sum(1, 2))
|
||||||
|
|
||||||
|
# Keyword arguments
|
||||||
|
|
||||||
|
def divide(dividend = 1, divisor = 1):
|
||||||
|
return dividend / divisor # Unsafe!!
|
||||||
|
|
||||||
|
print(divide())
|
||||||
|
print(divide(divisor = 2))
|
||||||
|
print(divide(dividend = 4, divisor = 2))
|
||||||
|
print(divide(divisor = 4, dividend = 2))
|
||||||
|
|
||||||
|
# Both argument types
|
||||||
|
|
||||||
|
def xnp(x, n, p = 1):
|
||||||
|
# Keyword args MUST appear AFTER positional args!
|
||||||
|
return (x * n) + p
|
||||||
|
|
||||||
|
# Variable length arguments
|
||||||
|
|
||||||
|
def varargs(*args):
|
||||||
|
for a in args:
|
||||||
|
print("Argument " + str(args.index(a)) + " is " + str(a))
|
||||||
|
|
||||||
|
varargs(1)
|
||||||
|
varargs(2, 3)
|
||||||
|
varargs(4, 5, 6)
|
||||||
|
|
||||||
|
# Variable keyword arguments
|
||||||
|
|
||||||
|
def varkwargs(**kwargs):
|
||||||
|
for k in kwargs.keys():
|
||||||
|
print('Argument "' + str(k) + '" is "' + str(kwargs[k]))
|
||||||
|
|
||||||
|
varkwargs(a = 1, b = 2, c = 3)
|
||||||
|
|
||||||
|
# Everything!
|
||||||
|
|
||||||
|
def allargs(a, b, c = None, *args, **kwargs):
|
||||||
|
print("a is " + str(a))
|
||||||
|
|
||||||
|
print("b is " + str(b))
|
||||||
|
|
||||||
|
if c is None:
|
||||||
|
print("c is None")
|
||||||
|
else:
|
||||||
|
print("c is Some")
|
||||||
|
|
||||||
|
for a in args:
|
||||||
|
print("Argument " + str(args.index(a)) + " is " + str(a))
|
||||||
|
|
||||||
|
for k in kwargs.keys():
|
||||||
|
print('Argument "' + str(k) + '" is "' + str(kwargs[k]))
|
||||||
|
|
||||||
|
allargs('a', 1, None, 2, 3, 4, q = "Hail", w = "Caesar!")
|
||||||
|
allargs(1, 2, c = 89)
|
||||||
|
|
||||||
|
# Nested functions
|
||||||
|
|
||||||
|
def outer(x):
|
||||||
|
def inner(y):
|
||||||
|
return x + y
|
||||||
|
|
||||||
|
return inner(9)
|
||||||
|
|
||||||
|
print(outer(1))
|
33
EVI - 2016/EVI - 33/Examples/classes.py
Normal file
33
EVI - 2016/EVI - 33/Examples/classes.py
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
################
|
||||||
|
# Simple class #
|
||||||
|
################
|
||||||
|
|
||||||
|
class Class(object):
|
||||||
|
def __init__(self, a):
|
||||||
|
self.a = a
|
||||||
|
|
||||||
|
def method(self):
|
||||||
|
return self.a
|
||||||
|
|
||||||
|
o = Class(1)
|
||||||
|
print(o.method())
|
||||||
|
print(o.a) # !
|
||||||
|
|
||||||
|
####################
|
||||||
|
# With inheritance #
|
||||||
|
####################
|
||||||
|
|
||||||
|
class Subclass(Class):
|
||||||
|
def __init__(self, a, b):
|
||||||
|
super(Subclass, self).__init__(a)
|
||||||
|
self.b = b
|
||||||
|
|
||||||
|
def method(self):
|
||||||
|
return self.b
|
||||||
|
|
||||||
|
def sub_method(self):
|
||||||
|
return self.a
|
||||||
|
|
||||||
|
s = Subclass(1, 2)
|
||||||
|
print(s.method())
|
||||||
|
print(s.sub_method())
|
36
EVI - 2016/EVI - 33/Examples/db.py
Normal file
36
EVI - 2016/EVI - 33/Examples/db.py
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import sqlite3
|
||||||
|
|
||||||
|
# "Connect" to a database
|
||||||
|
conn = sqlite3.connect('example.db')
|
||||||
|
|
||||||
|
# Get a cursor to operate on the database
|
||||||
|
c = conn.cursor()
|
||||||
|
|
||||||
|
# Create table
|
||||||
|
c.execute('''CREATE TABLE stocks
|
||||||
|
(date text, trans text, symbol text, qty real, price real)''')
|
||||||
|
|
||||||
|
# Insert a row of data
|
||||||
|
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
|
||||||
|
|
||||||
|
# Save (commit) the changes
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
# Select
|
||||||
|
t = ('RHAT',)
|
||||||
|
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
|
||||||
|
print(c.fetchone())
|
||||||
|
|
||||||
|
# Larger example that inserts many records at a time
|
||||||
|
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
|
||||||
|
('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
|
||||||
|
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
|
||||||
|
]
|
||||||
|
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
|
||||||
|
|
||||||
|
for row in c.execute('SELECT * FROM stocks ORDER BY price'):
|
||||||
|
print(row)
|
||||||
|
|
||||||
|
# We can also close the connection if we are done with it.
|
||||||
|
# Just be sure any changes have been committed or they will be lost.
|
||||||
|
conn.close()
|
28
EVI - 2016/EVI - 33/Examples/example.json
Normal file
28
EVI - 2016/EVI - 33/Examples/example.json
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
{
|
||||||
|
"firstName": "John",
|
||||||
|
"lastName": "Smith",
|
||||||
|
"isAlive": true,
|
||||||
|
"age": 25,
|
||||||
|
"address": {
|
||||||
|
"streetAddress": "21 2nd Street",
|
||||||
|
"city": "New York",
|
||||||
|
"state": "NY",
|
||||||
|
"postalCode": "10021-3100"
|
||||||
|
},
|
||||||
|
"phoneNumbers": [
|
||||||
|
{
|
||||||
|
"type": "home",
|
||||||
|
"number": "212 555-1234"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "office",
|
||||||
|
"number": "646 555-4567"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "mobile",
|
||||||
|
"number": "123 456-7890"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"children": [],
|
||||||
|
"spouse": null
|
||||||
|
}
|
31
EVI - 2016/EVI - 33/Examples/functional.py
Normal file
31
EVI - 2016/EVI - 33/Examples/functional.py
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
################################
|
||||||
|
# Lambda (anonymous) functions #
|
||||||
|
################################
|
||||||
|
|
||||||
|
f = lambda x, y: x + y
|
||||||
|
print(f(1, 2))
|
||||||
|
print()
|
||||||
|
|
||||||
|
##########################
|
||||||
|
# Higher order functions #
|
||||||
|
##########################
|
||||||
|
|
||||||
|
# Map: Applies a function to many lists. Returns a generator.
|
||||||
|
|
||||||
|
for i in map(lambda x: x*x, [1, 2, 3, 4, 5, 6]):
|
||||||
|
print(i)
|
||||||
|
print()
|
||||||
|
|
||||||
|
for i in map(f, [1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6, 7]):
|
||||||
|
print(i)
|
||||||
|
print()
|
||||||
|
|
||||||
|
# Custom higher order function
|
||||||
|
|
||||||
|
def hof(function = lambda x: x, *args):
|
||||||
|
for a in args:
|
||||||
|
print(function(a))
|
||||||
|
|
||||||
|
hof(lambda s: s.upper(), "a", "b", "c")
|
||||||
|
print()
|
||||||
|
hof(lambda x: x is None, 1, ["a", "b"], None, {})
|
46
EVI - 2016/EVI - 33/Examples/generators.py
Normal file
46
EVI - 2016/EVI - 33/Examples/generators.py
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
####################
|
||||||
|
# Generator object #
|
||||||
|
####################
|
||||||
|
|
||||||
|
def simple_generator():
|
||||||
|
i = 0
|
||||||
|
while(i < 10):
|
||||||
|
yield i
|
||||||
|
i += 1
|
||||||
|
raise StopIteration
|
||||||
|
|
||||||
|
g = simple_generator()
|
||||||
|
|
||||||
|
for i in g:
|
||||||
|
print(i)
|
||||||
|
|
||||||
|
try:
|
||||||
|
print(next(g))
|
||||||
|
except StopIteration:
|
||||||
|
print("Generator exhausted!")
|
||||||
|
else:
|
||||||
|
print("Generator success!")
|
||||||
|
finally:
|
||||||
|
print("At the end!")
|
||||||
|
|
||||||
|
####################
|
||||||
|
# Collection class #
|
||||||
|
####################
|
||||||
|
|
||||||
|
class Collection(object):
|
||||||
|
def __init__(self):
|
||||||
|
self.c = []
|
||||||
|
|
||||||
|
def add(self, x):
|
||||||
|
self.c.append(x)
|
||||||
|
|
||||||
|
def __iter__(self):
|
||||||
|
for i in self.c:
|
||||||
|
yield i
|
||||||
|
|
||||||
|
c = Collection()
|
||||||
|
c.add(1)
|
||||||
|
c.add(2)
|
||||||
|
c.add(3)
|
||||||
|
for i in c:
|
||||||
|
print(i)
|
9
EVI - 2016/EVI - 33/Examples/http_client.py
Normal file
9
EVI - 2016/EVI - 33/Examples/http_client.py
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import urllib2
|
||||||
|
|
||||||
|
# Create an HTTP request.
|
||||||
|
request = urllib2.Request("http://www.concisa.net.ve/2016/evi-2016-tutoriales/")
|
||||||
|
# Perform the request.
|
||||||
|
response = urllib2.urlopen(request)
|
||||||
|
# Get the response data.
|
||||||
|
document = response.read()
|
||||||
|
print(document)
|
8
EVI - 2016/EVI - 33/Examples/http_server.py
Normal file
8
EVI - 2016/EVI - 33/Examples/http_server.py
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
from http.server import HTTPServer, SimpleHTTPRequestHandler
|
||||||
|
|
||||||
|
def run(server_class = HTTPServer, handler_class = SimpleHTTPRequestHandler):
|
||||||
|
server_address = ('127.0.0.1', 8000)
|
||||||
|
httpd = server_class(server_address, handler_class)
|
||||||
|
httpd.serve_forever()
|
||||||
|
|
||||||
|
run()
|
16
EVI - 2016/EVI - 33/Examples/jsoning.py
Normal file
16
EVI - 2016/EVI - 33/Examples/jsoning.py
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import json
|
||||||
|
|
||||||
|
data = {"Name": "Miguel",
|
||||||
|
"Age": 27,
|
||||||
|
"ID": 18810993,
|
||||||
|
"info" : {"Height": 1.72,
|
||||||
|
"Weight": 80
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
with open("data.json", "w") as f:
|
||||||
|
f.write(json.dumps(data))
|
||||||
|
|
||||||
|
with open("example.json") as f:
|
||||||
|
j = json.loads(f.read())
|
||||||
|
print(j["isAlive"])
|
60
EVI - 2016/EVI - 33/Examples/lists.py
Normal file
60
EVI - 2016/EVI - 33/Examples/lists.py
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||||
|
|
||||||
|
#################
|
||||||
|
# List indexing #
|
||||||
|
#################
|
||||||
|
|
||||||
|
# Classical position indexing
|
||||||
|
|
||||||
|
i = 0
|
||||||
|
while i < len(a):
|
||||||
|
print(a[i])
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
# Negative indices
|
||||||
|
|
||||||
|
print(a[-1])
|
||||||
|
print(a[-2])
|
||||||
|
print(a[-3])
|
||||||
|
|
||||||
|
################
|
||||||
|
# List slicing #
|
||||||
|
################
|
||||||
|
|
||||||
|
# Elements between indices 3 and 7
|
||||||
|
|
||||||
|
print(a[3:7])
|
||||||
|
|
||||||
|
# Elements from index 5 onwards
|
||||||
|
|
||||||
|
print(a[5:])
|
||||||
|
|
||||||
|
# Elements from the start up to index 8
|
||||||
|
|
||||||
|
print(a[:8])
|
||||||
|
|
||||||
|
#######################
|
||||||
|
# List comprehensions #
|
||||||
|
#######################
|
||||||
|
|
||||||
|
# The first 10 square natural numbers
|
||||||
|
|
||||||
|
l = [x * x for x in range(1, 10)]
|
||||||
|
print(l)
|
||||||
|
|
||||||
|
# The first even square natural numbers
|
||||||
|
|
||||||
|
l = [x * x for x in range(1, 10) if (x * x) % 2 == 0]
|
||||||
|
print(l)
|
||||||
|
|
||||||
|
# Some numbers from the first list
|
||||||
|
|
||||||
|
l = [x for x in a if x > 2 and x < 7]
|
||||||
|
print(l)
|
||||||
|
|
||||||
|
#######
|
||||||
|
# zip #
|
||||||
|
#######
|
||||||
|
|
||||||
|
l = zip([1, 2, 3, 4], ["a", "b", "c"], ["Hello", ",", "World", "!"])
|
||||||
|
print(l)
|
16
EVI - 2016/EVI - 33/Examples/qsort.py
Normal file
16
EVI - 2016/EVI - 33/Examples/qsort.py
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import random as r
|
||||||
|
|
||||||
|
def qsort(l):
|
||||||
|
if len(l) == 0:
|
||||||
|
return []
|
||||||
|
elif len(l) == 1:
|
||||||
|
return l
|
||||||
|
else:
|
||||||
|
less = qsort([x for x in l[1:] if x <= l[0]])
|
||||||
|
more = qsort([x for x in l[1:] if x > l[0]])
|
||||||
|
return less + [l[0]] + more
|
||||||
|
|
||||||
|
a = [r.randint(0, 100) for x in xrange(100)]
|
||||||
|
b = qsort(a)
|
||||||
|
print a
|
||||||
|
print b
|
Reference in New Issue
Block a user