├── .gitignore ├── 61.py ├── README.md ├── bottle-test ├── bottle1.py ├── bottle2.py ├── bottle3.py ├── bottle_test.py └── index.html ├── chapter3 └── exercises.py ├── classfun.py ├── code.py ├── files.py ├── http_requests.py ├── links.py ├── named_tuple.py ├── regex.py ├── report.py ├── test1.py ├── test2.py └── weatherman.py /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | env 3 | __pycache__/ 4 | introducing-python.iml 5 | -------------------------------------------------------------------------------- /61.py: -------------------------------------------------------------------------------- 1 | print(61) 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # lubanovic-python 2 | 3 | These are notes I took from O'Reilly's "Introducing Python", written by an old friend, Bill Lubanovic. 4 | -------------------------------------------------------------------------------- /bottle-test/bottle1.py: -------------------------------------------------------------------------------- 1 | from bottle import route, run 2 | 3 | @route('/') 4 | def home(): 5 | return "It isn't fancy, but it's my home page" 6 | 7 | run(host='localhost', port=9999) 8 | -------------------------------------------------------------------------------- /bottle-test/bottle2.py: -------------------------------------------------------------------------------- 1 | from bottle import route, run, static_file 2 | 3 | @route('/') 4 | def main(): 5 | return static_file('index.html', '.') 6 | 7 | run(host='localhost', port=9999) 8 | -------------------------------------------------------------------------------- /bottle-test/bottle3.py: -------------------------------------------------------------------------------- 1 | from bottle import route, run, static_file 2 | 3 | @route('/') 4 | def main(): 5 | return static_file('index.html', '.') 6 | 7 | @route('/echo/') 8 | def echo(thing): 9 | return "Say hello to my little friend: %s!" % thing 10 | 11 | run(host='localhost', port=9999) 12 | -------------------------------------------------------------------------------- /bottle-test/bottle_test.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | resp = requests.get("http://localhost:9999/echo/Mothra") 4 | 5 | if resp.status_code == 200 and resp.text == "Say hello to my little friend: Mothra!": 6 | print("It worked! That almost never happens!") 7 | else: 8 | print("Argh, got this:", resp.text) 9 | 10 | -------------------------------------------------------------------------------- /bottle-test/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Bottle test homepage 6 | 7 | 8 | My new and improved home page!!! 9 | 10 | -------------------------------------------------------------------------------- /chapter3/exercises.py: -------------------------------------------------------------------------------- 1 | """ 2 | Exercises from chapter 3 for review 3 | """ 4 | 5 | 6 | def main(): 7 | birth_year = 1971 8 | years = 5 9 | years_list = [y for y in range(birth_year, birth_year + years + 1)] 10 | 11 | print("Year born: ", years_list[0]) 12 | print("Third birthday: ", years_list[3]) 13 | print("Last year:", years_list[-1]) 14 | 15 | things = ['mozzarella', 'cinderella', 'salmonella'] 16 | things[1] = things[1].capitalize() 17 | things[0] = things[0].upper() 18 | del things[-1] 19 | print(things) 20 | 21 | surprise = ['Groucho', 'Chico', 'Harpo'] 22 | surprise[-1] = surprise[-1].lower() 23 | surprise[-1] = surprise[-1][::-1] 24 | surprise[-1] = surprise[-1].capitalize() 25 | print(surprise) 26 | 27 | e2f = { 28 | 'dog': 'chien', 29 | 'cat': 'chat', 30 | 'walrus': 'morse' 31 | } 32 | 33 | print(e2f['walrus']) 34 | 35 | f2e = {} 36 | 37 | for eng, fr in e2f.items(): 38 | f2e[fr] = eng 39 | 40 | print(f2e['morse']) 41 | 42 | if __name__ == '__main__': 43 | main() 44 | -------------------------------------------------------------------------------- /classfun.py: -------------------------------------------------------------------------------- 1 | class Car: 2 | make = None 3 | model = None 4 | __theYear = None 5 | count = 0 6 | 7 | @property 8 | def description(self): 9 | Car.count += 1 10 | if self.__theYear and self.make and self.model: 11 | return str(self.__theYear) + ' ' + self.make + ' ' + self.model 12 | else: 13 | return 'Unknown' 14 | 15 | def get_year(self): 16 | return self.__theYear 17 | 18 | def set_year(self, year): 19 | self.__theYear = year 20 | 21 | year = property(get_year, set_year) 22 | 23 | @classmethod 24 | def fleet_size(cls): 25 | return cls.count 26 | 27 | @staticmethod 28 | def define(): 29 | print("A car carries one or more people and has 4 wheels.") 30 | 31 | 32 | class Jeep(Car): 33 | def __init__(self): 34 | super().__init__() 35 | self.make = 'Jeep' 36 | self.trailRated = True 37 | 38 | # playground 39 | # ride = Car() 40 | # print("Description:", ride.description) 41 | 42 | funRide = Jeep() 43 | funRide.model = 'Wrangler' 44 | funRide.year = 2015 45 | print("Description:", funRide.description) 46 | 47 | plainRide = Car() 48 | plainRide.make = 'Ford' 49 | plainRide.model = 'Fiesta' 50 | plainRide.set_year(1989) 51 | print("Description:", plainRide.description) 52 | 53 | otherRide = Car() 54 | otherRide.make = 'Ford' 55 | otherRide.model = 'Pinto' 56 | otherRide.set_year(1971) 57 | print("Description:", otherRide.description) 58 | 59 | print("There are", Car.fleet_size(), 'cars.') 60 | Jeep.define() 61 | -------------------------------------------------------------------------------- /code.py: -------------------------------------------------------------------------------- 1 | name = 'Hello there everybody' 2 | print(name.upper()) 3 | print(name.endswith('body')) 4 | print(name.isalpha()) 5 | print(name.swapcase()) 6 | print(name[3:9]) 7 | 8 | theList = [] 9 | print(theList) 10 | 11 | anotherList = list() 12 | print(anotherList) 13 | 14 | letters = list('hello') 15 | print(letters) 16 | 17 | birthday = '12/26/1971' 18 | print(birthday.split('/')) 19 | 20 | otherName = list('Wanda') 21 | otherName[2] = 'f' 22 | print(''.join(otherName)) 23 | 24 | newList = ['one', 'two', 'three'] 25 | print(newList) 26 | 27 | print(newList[0:1]) 28 | 29 | reversedList = newList[::-1] 30 | print(reversedList) 31 | 32 | reversedList.append('zero') 33 | print(reversedList) 34 | 35 | arr1 = ['i1', 'i2'] 36 | arr2 = ['i3', 'i4'] 37 | 38 | arr3 = arr1 + arr2 39 | print(arr3) 40 | 41 | del(arr3[-1]) 42 | print(arr3) 43 | 44 | arr3.remove('i2') 45 | print(arr3) 46 | 47 | more = ['i5', 'i6'] 48 | 49 | arr3 += more 50 | 51 | print(arr3.pop()) 52 | print(arr3.pop(1)) 53 | 54 | print(arr3) 55 | 56 | print('i3' in arr3) 57 | print('i1' in arr3) 58 | 59 | print(arr3.index('i5')) 60 | 61 | names = ['Joe', 'Max', 'Scott', 'Brian'] 62 | print('sorted:', sorted(names)) 63 | print('unsorted:', names) 64 | names.sort() # sort in place 65 | print('internal sort', names) 66 | 67 | print(len(names)) 68 | 69 | arr = [1, 2, 3] 70 | print(arr) 71 | 72 | anotherArr = arr 73 | anotherArr[1] = 'two' 74 | 75 | # same reference 76 | print(arr) 77 | print(anotherArr) 78 | 79 | newArr = [1, 2, 3] 80 | copyArr = newArr.copy() 81 | copyArr[1] = 'two' 82 | 83 | print(newArr) 84 | 85 | a, b, c = copyArr 86 | 87 | print(b) 88 | 89 | dicty = { 90 | "name": "John", 91 | "address": "123 Main St.", 92 | } 93 | 94 | print(dicty['name']) 95 | 96 | myDict = {} 97 | myDict['name'] = 'Joe' 98 | myDict['birthdate'] = '2/14/1984' 99 | print(myDict) 100 | 101 | newInfo = { 102 | 'birthdate': '3/14/1984', 103 | } 104 | 105 | print("updating") 106 | 107 | myDict.update(newInfo) 108 | print(myDict) 109 | 110 | nameInDict = 'name' in myDict 111 | ageInDict = 'age' in myDict 112 | 113 | print(nameInDict) 114 | print(ageInDict) 115 | 116 | val = myDict.get('name', False) 117 | 118 | print(val) 119 | 120 | # python returns list 121 | # python3 returns dict_keys() 122 | print(myDict.keys()) 123 | print(myDict.values()) 124 | print(myDict.items()) 125 | 126 | dictCopy = myDict.copy() 127 | print(myDict.keys()) 128 | 129 | drinks = { 130 | 'martini': {'vodka', 'vermouth'}, 131 | 'black russian': {'vodka', 'kahlua'}, 132 | 'white russian': {'cream', 'kahlua', 'vodka'}, 133 | 'manhattan': {'rye', 'vermouth', 'bitters'}, 134 | 'screwdriver': {'orange juice', 'vodka'} 135 | } 136 | 137 | for drink, ingredients in drinks.items(): 138 | if 'vodka' in ingredients: 139 | print('has vodka:', drink) 140 | 141 | testList = ['one', 'capme', 'three'] 142 | upperStr = testList[1].upper() 143 | print(upperStr) 144 | 145 | print('===== logic =====') 146 | 147 | foo = 1 148 | if foo: 149 | print("we got foo") 150 | 151 | count = 1 152 | while count <= 5: 153 | print(count) 154 | count += 1 155 | 156 | print('===== while loop with input and break =====') 157 | 158 | # while True: 159 | # value = input("type a word to capitalize [q or enter to exit]: ") 160 | # if value == 'q' or value == '': 161 | # print('All done.') 162 | # break 163 | # else: 164 | # print(value.capitalize()) 165 | 166 | print('===== hitting else when break wasn\'t hit =====') 167 | 168 | numbers = [1, 3, 5] 169 | position = 0 170 | length = len(numbers) 171 | while position < length: 172 | number = numbers[position] 173 | if number % 2 == 0: # even 174 | print('Found even number: ', number) 175 | break 176 | position += 1 177 | else: 178 | print('No even numbers found') 179 | 180 | print('===== list comprehension =====') 181 | 182 | rows = range(5, 10) # last in range is never reached. it's y - 1 183 | cols = range(1, 5) 184 | cells = [(row, col) for row in rows for col in cols if row % 2 == 0] # even rows only 185 | 186 | # unpack 187 | for row, col in cells: 188 | print("row:", row, "col:", col) 189 | 190 | print('===== dictionary comprehension =====') 191 | 192 | word = 'letters' 193 | letterCounts = {letter: word.count(letter) for letter in word} 194 | print(letterCounts) 195 | 196 | print('===== functions =====') 197 | 198 | 199 | def dinner(wine, entree, dessert): 200 | return {'wine': wine, 'entree': entree, 'dessert': dessert} 201 | 202 | print(dinner(dessert='pie', wine='malbec', entree='steak')) 203 | 204 | # Using * with arguments 205 | 206 | 207 | def my_func(*args): 208 | """returns an arg list""" 209 | return args 210 | 211 | print(my_func('me', 'myself', 'I')) 212 | 213 | 214 | def my_other_func(**kwargs): 215 | return kwargs 216 | 217 | print(my_other_func(self='me', other='myself', other2='I')) 218 | 219 | -------------------------------------------------------------------------------- /files.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | os.mkdir('dir1') 4 | os.mkdir('dir1/subdir1') 5 | 6 | with open('dir1/subdir1/somefile', 'wt') as fout: 7 | fout.write('this was a short-lived file') 8 | 9 | os.unlink('dir1/subdir1/somefile') 10 | 11 | os.rmdir('dir1/subdir1') 12 | os.rmdir('dir1') 13 | -------------------------------------------------------------------------------- /http_requests.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | 4 | url = 'http://api.icndb.com/jokes/random' 5 | resp = requests.get(url) 6 | 7 | # print(resp.status_code) 8 | # print(resp.text) 9 | 10 | if resp.status_code == 200: 11 | jokeObj = json.loads(resp.text) 12 | print(jokeObj['value']['joke']) 13 | else: 14 | raise Exception("I failed to get the joke.") 15 | -------------------------------------------------------------------------------- /links.py: -------------------------------------------------------------------------------- 1 | def get_links(url): 2 | import requests 3 | from bs4 import BeautifulSoup as soup 4 | result = requests.get(url) 5 | page = result.text 6 | doc = soup(page) 7 | 8 | links = [element.get('href') for element in doc.find_all('a')] 9 | return links 10 | 11 | if __name__ == '__main__': 12 | import sys 13 | for url in sys.argv[1:]: 14 | print("Links in", url) 15 | for num, link in enumerate(get_links(url), start=1): 16 | print(num, link) 17 | print() 18 | 19 | -------------------------------------------------------------------------------- /named_tuple.py: -------------------------------------------------------------------------------- 1 | # can create a class-like immutable object as a named tuple 2 | 3 | from collections import namedtuple 4 | 5 | Duck = namedtuple('Duck', 'color bill tail') 6 | 7 | duck1 = Duck('green', 'yellow', 'short') 8 | duck2 = Duck(bill='gnarly', tail='long', color='red') 9 | 10 | # duck1.color = 'green' 11 | # duck1.bill = 'yellow' 12 | # duck1.tail = 'short' 13 | 14 | print(duck1.color) 15 | print(duck1.bill) 16 | print(duck1.tail) 17 | # print(duck1.thing) 18 | 19 | # duck1.tail = 'long' 20 | # print(duck1.color) 21 | # print(duck1.bill) 22 | # print(duck1.tail) 23 | 24 | print(duck2.color) 25 | print(duck2.bill) 26 | print(duck2.tail) 27 | -------------------------------------------------------------------------------- /regex.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | title = 'Young Frankenstein' 4 | 5 | m1 = re.match('You', title) 6 | if m1: 7 | print(m1.group()) 8 | 9 | m2 = re.match('Frank', title) 10 | if m2: 11 | print(m2.group()) 12 | else: 13 | print("Did not match from beginning") 14 | 15 | # match() only matches at beginning, case sensitive 16 | 17 | m3 = re.search('Frank', title) 18 | if m3: 19 | print(m3.group()) 20 | else: 21 | print("Did not find it anywhere") 22 | 23 | m4 = re.match('.*Frank', title) 24 | if m4: 25 | print(m4.group()) 26 | else: 27 | print("Did not find with star") 28 | 29 | m5 = re.findall('n.?', title) 30 | if m5: 31 | print(m5) 32 | else: 33 | print("Did not find any") 34 | 35 | print(re.split('n', title)) 36 | 37 | print(re.sub('n', 'X', title)) # sub = replace 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /report.py: -------------------------------------------------------------------------------- 1 | def get_description(): 2 | """Return random weather, just like the pros""" 3 | from random import choice 4 | possibilities = ['rain', 'snow', 'sleet', 'fog', 'sun', 'who knows'] 5 | return choice(possibilities) 6 | 7 | 8 | -------------------------------------------------------------------------------- /test1.py: -------------------------------------------------------------------------------- 1 | print("I'm a standalone program!") 2 | -------------------------------------------------------------------------------- /test2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | print('Program arguments:', sys.argv) 3 | 4 | -------------------------------------------------------------------------------- /weatherman.py: -------------------------------------------------------------------------------- 1 | import report 2 | 3 | description = report.get_description() 4 | print("Today's weather:", description) 5 | --------------------------------------------------------------------------------