Added files for Ecoanova's Python 3 course.
8
Ecoanova/Introduccion a Python 3/Ejemplos/RSP/LICENSE
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
"THE BEER-WARE LICENSE" (Revision 42):
|
||||||
|
|
||||||
|
<sonofgrendel@gmail.com> wrote this file. As long as you retain this
|
||||||
|
notice you can do whatever you want with this stuff. If we meet some
|
||||||
|
day, and you think this stuff is worth it, you can buy me a beer in
|
||||||
|
return.
|
||||||
|
|
||||||
|
Miguel Angel Astor.
|
7
Ecoanova/Introduccion a Python 3/Ejemplos/RSP/README.org
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
* RSP: Rock Scissors Paper
|
||||||
|
|
||||||
|
RSP is a Python 3 clone of the classic MacOS software toy from 1996
|
||||||
|
[[https://macintoshgarden.org/games/rock-scissors-paper][Rock Scissors Paper]] by shareware publisher Argus IG.
|
||||||
|
|
||||||
|
#+ATTR_HTML: :alt Playing rock paper scissors against a robot. :align center
|
||||||
|
[[file:rsp2.png]]
|
After Width: | Height: | Size: 557 B |
After Width: | Height: | Size: 799 B |
After Width: | Height: | Size: 553 B |
After Width: | Height: | Size: 2.3 KiB |
After Width: | Height: | Size: 2.7 KiB |
After Width: | Height: | Size: 2.7 KiB |
After Width: | Height: | Size: 2.7 KiB |
After Width: | Height: | Size: 3.0 KiB |
After Width: | Height: | Size: 3.0 KiB |
After Width: | Height: | Size: 3.0 KiB |
After Width: | Height: | Size: 2.7 KiB |
After Width: | Height: | Size: 2.7 KiB |
After Width: | Height: | Size: 2.7 KiB |
BIN
Ecoanova/Introduccion a Python 3/Ejemplos/RSP/rsp2.png
Normal file
After Width: | Height: | Size: 4.2 KiB |
176
Ecoanova/Introduccion a Python 3/Ejemplos/RSP/rsvp.py
Normal file
@@ -0,0 +1,176 @@
|
|||||||
|
#! /usr/bin/env python3
|
||||||
|
|
||||||
|
import random as r
|
||||||
|
import threading as th
|
||||||
|
import tkinter as tk
|
||||||
|
|
||||||
|
# Gampelay constants
|
||||||
|
ROCK = 0
|
||||||
|
SCISSORS = 1
|
||||||
|
PAPER = 2
|
||||||
|
|
||||||
|
# Score variables
|
||||||
|
PLAYER_SCORE = 0
|
||||||
|
EYEGUY_SCORE = 0
|
||||||
|
|
||||||
|
# Threading timer object
|
||||||
|
TIMER = None
|
||||||
|
|
||||||
|
def main():
|
||||||
|
""" Main method of the game. """
|
||||||
|
|
||||||
|
def reset():
|
||||||
|
""" Restarts the game. """
|
||||||
|
global PLAYER_SCORE, EYEGUY_SCORE
|
||||||
|
PLAYER_SCORE = 0
|
||||||
|
EYEGUY_SCORE = 0
|
||||||
|
player_label["text"] = "Humanoid> " + str(PLAYER_SCORE)
|
||||||
|
eyeguy_label["text"] = str(EYEGUY_SCORE) + " <EyeGuy"
|
||||||
|
alien_at_ease()
|
||||||
|
|
||||||
|
def alien_at_ease():
|
||||||
|
""" Resets the EyeGuy label to it's base resting state. """
|
||||||
|
global TIMER
|
||||||
|
eyeguy.config(image = alien_graphics["resting"])
|
||||||
|
print("Eyeguy is resting.")
|
||||||
|
TIMER = None
|
||||||
|
|
||||||
|
def quit_game():
|
||||||
|
""" Cancels any pending timer ad closes the window. """
|
||||||
|
if TIMER is not None:
|
||||||
|
TIMER.cancel()
|
||||||
|
window.quit()
|
||||||
|
|
||||||
|
def play(player_choice):
|
||||||
|
""" Evaluates a game turn. """
|
||||||
|
global PLAYER_SCORE, EYEGUY_SCORE, TIMER
|
||||||
|
|
||||||
|
def choice2str(choice):
|
||||||
|
""" Returns the name of a gameplay move as a string. """
|
||||||
|
return "ROCK" if choice == ROCK else \
|
||||||
|
("SCISSORS" if choice == SCISSORS else "PAPER")
|
||||||
|
|
||||||
|
# Get EyeGuy's move
|
||||||
|
alien_choice = r.randrange(3)
|
||||||
|
|
||||||
|
# Check the outcome of this turn
|
||||||
|
if (alien_choice == ROCK and player_choice == SCISSORS) or \
|
||||||
|
(alien_choice == SCISSORS and player_choice == PAPER) or \
|
||||||
|
(alien_choice == PAPER and player_choice == ROCK):
|
||||||
|
# Check if EyeGuy won
|
||||||
|
print("Eyeguy won! " + choice2str(alien_choice) + " beats " + choice2str(player_choice))
|
||||||
|
EYEGUY_SCORE += 1
|
||||||
|
|
||||||
|
# Update EyeGuy's sprite
|
||||||
|
if alien_choice == ROCK:
|
||||||
|
eyeguy.config(image = alien_graphics["rock_win"])
|
||||||
|
elif alien_choice == SCISSORS:
|
||||||
|
eyeguy.config(image = alien_graphics["scsr_win"])
|
||||||
|
else:
|
||||||
|
eyeguy.config(image = alien_graphics["papr_win"])
|
||||||
|
|
||||||
|
elif (alien_choice == ROCK and player_choice == PAPER) or \
|
||||||
|
(alien_choice == SCISSORS and player_choice == ROCK) or \
|
||||||
|
(alien_choice == PAPER and player_choice == SCISSORS):
|
||||||
|
# Check if EyeGuy lost
|
||||||
|
print("Player won! " + choice2str(player_choice) + " beats " + choice2str(alien_choice))
|
||||||
|
PLAYER_SCORE += 1
|
||||||
|
|
||||||
|
# Update EyeGuy's sprite
|
||||||
|
if alien_choice == ROCK:
|
||||||
|
eyeguy.config(image = alien_graphics["rock_dft"])
|
||||||
|
elif alien_choice == SCISSORS:
|
||||||
|
eyeguy.config(image = alien_graphics["scsr_dft"])
|
||||||
|
else:
|
||||||
|
eyeguy.config(image = alien_graphics["papr_dft"])
|
||||||
|
|
||||||
|
else:
|
||||||
|
# Else its a tie
|
||||||
|
print(choice2str(alien_choice) + " and " + choice2str(player_choice) + " is a tie!")
|
||||||
|
|
||||||
|
# Update EyeGuy's sprite
|
||||||
|
if alien_choice == ROCK:
|
||||||
|
eyeguy.config(image = alien_graphics["rock_tie"])
|
||||||
|
elif alien_choice == SCISSORS:
|
||||||
|
eyeguy.config(image = alien_graphics["scsr_tie"])
|
||||||
|
else:
|
||||||
|
eyeguy.config(image = alien_graphics["papr_tie"])
|
||||||
|
|
||||||
|
# Update the score labels
|
||||||
|
player_label["text"] = "Humanoid> " + str(PLAYER_SCORE)
|
||||||
|
eyeguy_label["text"] = str(EYEGUY_SCORE) + " <EyeGuy"
|
||||||
|
|
||||||
|
# Set a timer to reset EyeGuy's sprite after 3 seconds
|
||||||
|
if TIMER is not None:
|
||||||
|
print("Canceled!")
|
||||||
|
TIMER.cancel()
|
||||||
|
TIMER = th.Timer(3, alien_at_ease)
|
||||||
|
TIMER.start()
|
||||||
|
|
||||||
|
# Create the game window
|
||||||
|
window = tk.Tk()
|
||||||
|
window.wm_title("Rock and Scissors VS Paper")
|
||||||
|
window.wm_resizable(width = tk.FALSE, height = tk.FALSE)
|
||||||
|
|
||||||
|
# Create the main menu bar
|
||||||
|
menubar = tk.Menu(window)
|
||||||
|
|
||||||
|
# Create the "game" menu option
|
||||||
|
game_menu = tk.Menu(menubar, tearoff = 0)
|
||||||
|
game_menu.add_command(label = "New Game", command = reset)
|
||||||
|
game_menu.add_command(label = "Quit", command = quit_game)
|
||||||
|
|
||||||
|
# Add the menu options to the menu bar
|
||||||
|
menubar.add_cascade(label = "Game", menu = game_menu)
|
||||||
|
window.config(menu = menubar)
|
||||||
|
|
||||||
|
# Load EyeGuy's sprites
|
||||||
|
alien_graphics = {
|
||||||
|
"resting" : tk.PhotoImage(file = "assets/gfx/eyeguy.1.1.png"),
|
||||||
|
"rock_tie" : tk.PhotoImage(file = "assets/gfx/eyeguy.2.1.png"),
|
||||||
|
"rock_win" : tk.PhotoImage(file = "assets/gfx/eyeguy.2.2.png"),
|
||||||
|
"rock_dft" : tk.PhotoImage(file = "assets/gfx/eyeguy.2.3.png"),
|
||||||
|
"scsr_tie" : tk.PhotoImage(file = "assets/gfx/eyeguy.3.1.png"),
|
||||||
|
"scsr_win" : tk.PhotoImage(file = "assets/gfx/eyeguy.3.2.png"),
|
||||||
|
"scsr_dft" : tk.PhotoImage(file = "assets/gfx/eyeguy.3.3.png"),
|
||||||
|
"papr_tie" : tk.PhotoImage(file = "assets/gfx/eyeguy.4.1.png"),
|
||||||
|
"papr_win" : tk.PhotoImage(file = "assets/gfx/eyeguy.4.2.png"),
|
||||||
|
"papr_dft" : tk.PhotoImage(file = "assets/gfx/eyeguy.4.3.png")
|
||||||
|
}
|
||||||
|
|
||||||
|
# Create and set the score labels
|
||||||
|
player_label = tk.Label(window, text = "Humanoid> " + str(PLAYER_SCORE), fg = "red")
|
||||||
|
player_label.grid(row = 0, column = 0)
|
||||||
|
eyeguy_label = tk.Label(window, text = str(EYEGUY_SCORE) + " <EyeGuy", fg = "blue")
|
||||||
|
eyeguy_label.grid(row = 0, column = 2)
|
||||||
|
|
||||||
|
# Create and set EyeGuy's sprite label
|
||||||
|
eyeguy = tk.Label(window, image = alien_graphics["resting"])
|
||||||
|
eyeguy.grid(row = 1, column = 0, columnspan = 3)
|
||||||
|
|
||||||
|
# Load the icons for the buttons
|
||||||
|
btn_icons = [tk.PhotoImage(file = "assets/gfx/btn.1.png"),
|
||||||
|
tk.PhotoImage(file = "assets/gfx/btn.2.png"),
|
||||||
|
tk.PhotoImage(file = "assets/gfx/btn.3.png")]
|
||||||
|
|
||||||
|
# Create and set each button
|
||||||
|
rock_btn = tk.Button(window, image = btn_icons[0], relief = tk.FLAT, command = lambda: play(0))
|
||||||
|
rock_btn.grid(row = 2, column = 0)
|
||||||
|
scsr_btn = tk.Button(window, image = btn_icons[1], relief = tk.FLAT, command = lambda: play(1))
|
||||||
|
scsr_btn.grid(row = 2, column = 1)
|
||||||
|
papr_btn = tk.Button(window, image = btn_icons[2], relief = tk.FLAT, command = lambda: play(2))
|
||||||
|
papr_btn.grid(row = 2, column = 2)
|
||||||
|
|
||||||
|
# Create and set the author label
|
||||||
|
text = tk.Label(window, text = "http://github.com/miky-kr5/")
|
||||||
|
text.grid(row = 3, column = 0, columnspan = 3)
|
||||||
|
|
||||||
|
# Show the window
|
||||||
|
try:
|
||||||
|
window.mainloop()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("Interrupted...")
|
||||||
|
|
||||||
|
# Game entry point
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
132
Ecoanova/Introduccion a Python 3/Ejemplos/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
Ecoanova/Introduccion a Python 3/Ejemplos/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
Ecoanova/Introduccion a Python 3/Ejemplos/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
Ecoanova/Introduccion a Python 3/Ejemplos/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
Ecoanova/Introduccion a Python 3/Ejemplos/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
Ecoanova/Introduccion a Python 3/Ejemplos/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)
|
7
Ecoanova/Introduccion a Python 3/Ejemplos/http_client.py
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import urllib.request
|
||||||
|
|
||||||
|
# Create an HTTP request and get the response.
|
||||||
|
response = urllib.request.urlopen("http://www.concisa.net.ve/2016/evi-2016-tutoriales/")
|
||||||
|
# Get the response data.
|
||||||
|
document = response.read()
|
||||||
|
print(document)
|
8
Ecoanova/Introduccion a Python 3/Ejemplos/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
Ecoanova/Introduccion a Python 3/Ejemplos/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
Ecoanova/Introduccion a Python 3/Ejemplos/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 = [x for x in zip([1, 2, 3, 4], ["a", "b", "c"], ["Hello", ",", "World", "!"])]
|
||||||
|
print(l)
|
16
Ecoanova/Introduccion a Python 3/Ejemplos/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 range(100)]
|
||||||
|
b = qsort(a)
|
||||||
|
print(a)
|
||||||
|
print(b)
|