From 8bff850da30b2335c87687fbbdd90f1d49fb2969 Mon Sep 17 00:00:00 2001 From: "Zed A. Shaw" Date: Sun, 23 Mar 2025 22:09:05 -0400 Subject: [PATCH] First commit of the code from the course for people to access. --- .gitignore | 1 + python/code/module-1/ex1.err | 6 + python/code/module-1/ex1.py | 7 + python/code/module-1/ex10.py | 15 ++ python/code/module-1/ex11.py | 14 ++ python/code/module-1/ex12.py | 11 ++ python/code/module-1/ex13.py | 9 ++ python/code/module-1/ex14.py | 29 ++++ python/code/module-1/ex15.py | 22 +++ python/code/module-1/ex15_sample.txt | 4 + python/code/module-1/ex16.py | 38 +++++ python/code/module-1/ex17.py | 29 ++++ python/code/module-1/ex2.py | 10 ++ python/code/module-1/ex3.py | 23 +++ python/code/module-1/ex4.err | 4 + python/code/module-1/ex4.py | 18 +++ python/code/module-1/ex5.py | 19 +++ python/code/module-1/ex6.py | 22 +++ python/code/module-1/ex7.py | 21 +++ python/code/module-1/ex8.py | 13 ++ python/code/module-1/ex9.py | 14 ++ python/code/module-1/fake_input.py | 13 ++ python/code/module-1/new_file.txt | 3 + python/code/module-1/new_test.txt | 3 + python/code/module-1/test.txt | 3 + python/code/module-2/ex18.py | 25 ++++ python/code/module-2/ex18_demo.py | 31 ++++ python/code/module-2/ex19.py | 26 ++++ python/code/module-2/ex20.py | 33 +++++ python/code/module-2/ex20_test.txt | 3 + python/code/module-2/ex21.py | 36 +++++ python/code/module-2/ex22.py | 23 +++ python/code/module-2/ex23.py | 18 +++ python/code/module-2/ex24.py | 30 ++++ python/code/module-2/ex25.py | 38 +++++ python/code/module-2/ex25_pycon.py | 16 ++ python/code/module-2/ex26.py | 2 + python/code/module-2/ex26_code.py | 31 ++++ python/code/module-2/ex28.py | 1 + python/code/module-2/ex30.py | 31 ++++ python/code/module-2/ex31.py | 27 ++++ python/code/module-2/ex32.py | 49 ++++++ python/code/module-2/ex32_dis.py | 13 ++ python/code/module-2/ex33.py | 31 ++++ python/code/module-2/ex34.py | 18 +++ python/code/module-2/ex35.py | 87 +++++++++++ python/code/module-2/ex36.py | 1 + python/code/module-2/ex37.py | 1 + python/code/module-2/fake_input.py | 13 ++ python/code/module-2/languages.txt | 97 ++++++++++++ python/code/module-3/ex38.py | 25 ++++ python/code/module-3/ex39.py | 62 ++++++++ python/code/module-3/ex39_pycon.py | 23 +++ python/code/module-3/ex40.py | 21 +++ python/code/module-3/ex40a.py | 68 +++++++++ python/code/module-3/ex41.py | 3 + python/code/module-3/ex42.py | 25 ++++ python/code/module-3/ex42_demo.py | 38 +++++ python/code/module-3/ex43.py | 62 ++++++++ python/code/module-3/ex43_classes.py | 57 +++++++ python/code/module-3/ex43_pycon.py | 23 +++ python/code/module-3/ex43_pycon_out.py | 37 +++++ python/code/module-3/ex44_1.py | 10 ++ python/code/module-3/ex44_2.py | 11 ++ python/code/module-3/ex44_3.py | 20 +++ python/code/module-3/ex44_4.py | 17 +++ python/code/module-3/ex45.py | 13 ++ python/code/module-3/ex46.py | 78 ++++++++++ python/code/module-3/ex47.py | 180 +++++++++++++++++++++++ python/code/module-3/ex47.sh-session | 6 + python/code/module-3/ex47/__init__.py | 0 python/code/module-3/ex47/game.py | 16 ++ python/code/module-3/ex47_classes.py | 57 +++++++ python/code/module-3/ex47_dialogue.py | 107 ++++++++++++++ python/code/module-3/ex47_tests.py | 33 +++++ python/code/module-3/ex48_convert.py | 6 + python/code/module-3/ex48_pycon.py | 1 + python/code/module-3/ex48a.py | 13 ++ python/code/module-3/ex48b.py | 15 ++ python/code/module-3/ex48c.py | 17 +++ python/code/module-3/ex48d.py | 33 +++++ python/code/module-3/ex48e.py | 32 ++++ python/code/module-3/ex49_pycon.py | 4 + python/code/module-3/ex49a_pycon.py | 10 ++ python/code/module-3/ex50.py | 11 ++ python/code/module-3/ex50_except.py | 9 ++ python/code/module-3/ex50_test.py | 15 ++ python/code/module-3/fake_input.py | 13 ++ python/code/module-3/languages.txt | 97 ++++++++++++ python/code/module-3/lexicon_tests.py | 49 ++++++ python/code/module-3/mystuff.py | 2 + python/code/module-3/new_file.txt | 3 + python/code/module-3/setup.py | 20 +++ python/code/module-3/test.txt | 3 + python/code/module-3/tests/__init__.py | 0 python/code/module-3/tests/ex47_tests.py | 33 +++++ python/code/module-4/euro_migrate.sql | 14 ++ python/code/module-4/ex51.py | 19 +++ python/code/module-4/ex51_clue.py | 28 ++++ python/code/module-4/ex52.py | 18 +++ python/code/module-4/ex53.py | 20 +++ python/code/module-4/ex54.py | 18 +++ python/code/module-4/ex57.py | 11 ++ python/code/module-4/ex58.py | 21 +++ python/code/module-4/ex62.py | 1 + 105 files changed, 2560 insertions(+) create mode 100644 python/code/module-1/ex1.err create mode 100644 python/code/module-1/ex1.py create mode 100644 python/code/module-1/ex10.py create mode 100644 python/code/module-1/ex11.py create mode 100644 python/code/module-1/ex12.py create mode 100644 python/code/module-1/ex13.py create mode 100644 python/code/module-1/ex14.py create mode 100644 python/code/module-1/ex15.py create mode 100644 python/code/module-1/ex15_sample.txt create mode 100644 python/code/module-1/ex16.py create mode 100644 python/code/module-1/ex17.py create mode 100644 python/code/module-1/ex2.py create mode 100644 python/code/module-1/ex3.py create mode 100644 python/code/module-1/ex4.err create mode 100644 python/code/module-1/ex4.py create mode 100644 python/code/module-1/ex5.py create mode 100644 python/code/module-1/ex6.py create mode 100644 python/code/module-1/ex7.py create mode 100644 python/code/module-1/ex8.py create mode 100644 python/code/module-1/ex9.py create mode 100644 python/code/module-1/fake_input.py create mode 100644 python/code/module-1/new_file.txt create mode 100644 python/code/module-1/new_test.txt create mode 100644 python/code/module-1/test.txt create mode 100644 python/code/module-2/ex18.py create mode 100644 python/code/module-2/ex18_demo.py create mode 100644 python/code/module-2/ex19.py create mode 100644 python/code/module-2/ex20.py create mode 100644 python/code/module-2/ex20_test.txt create mode 100644 python/code/module-2/ex21.py create mode 100644 python/code/module-2/ex22.py create mode 100644 python/code/module-2/ex23.py create mode 100644 python/code/module-2/ex24.py create mode 100644 python/code/module-2/ex25.py create mode 100644 python/code/module-2/ex25_pycon.py create mode 100644 python/code/module-2/ex26.py create mode 100644 python/code/module-2/ex26_code.py create mode 100644 python/code/module-2/ex28.py create mode 100644 python/code/module-2/ex30.py create mode 100644 python/code/module-2/ex31.py create mode 100644 python/code/module-2/ex32.py create mode 100644 python/code/module-2/ex32_dis.py create mode 100644 python/code/module-2/ex33.py create mode 100644 python/code/module-2/ex34.py create mode 100644 python/code/module-2/ex35.py create mode 100644 python/code/module-2/ex36.py create mode 100644 python/code/module-2/ex37.py create mode 100644 python/code/module-2/fake_input.py create mode 100644 python/code/module-2/languages.txt create mode 100644 python/code/module-3/ex38.py create mode 100644 python/code/module-3/ex39.py create mode 100644 python/code/module-3/ex39_pycon.py create mode 100644 python/code/module-3/ex40.py create mode 100644 python/code/module-3/ex40a.py create mode 100644 python/code/module-3/ex41.py create mode 100644 python/code/module-3/ex42.py create mode 100644 python/code/module-3/ex42_demo.py create mode 100644 python/code/module-3/ex43.py create mode 100644 python/code/module-3/ex43_classes.py create mode 100644 python/code/module-3/ex43_pycon.py create mode 100644 python/code/module-3/ex43_pycon_out.py create mode 100644 python/code/module-3/ex44_1.py create mode 100644 python/code/module-3/ex44_2.py create mode 100644 python/code/module-3/ex44_3.py create mode 100644 python/code/module-3/ex44_4.py create mode 100644 python/code/module-3/ex45.py create mode 100644 python/code/module-3/ex46.py create mode 100644 python/code/module-3/ex47.py create mode 100644 python/code/module-3/ex47.sh-session create mode 100644 python/code/module-3/ex47/__init__.py create mode 100644 python/code/module-3/ex47/game.py create mode 100644 python/code/module-3/ex47_classes.py create mode 100644 python/code/module-3/ex47_dialogue.py create mode 100644 python/code/module-3/ex47_tests.py create mode 100644 python/code/module-3/ex48_convert.py create mode 100644 python/code/module-3/ex48_pycon.py create mode 100644 python/code/module-3/ex48a.py create mode 100644 python/code/module-3/ex48b.py create mode 100644 python/code/module-3/ex48c.py create mode 100644 python/code/module-3/ex48d.py create mode 100644 python/code/module-3/ex48e.py create mode 100644 python/code/module-3/ex49_pycon.py create mode 100644 python/code/module-3/ex49a_pycon.py create mode 100644 python/code/module-3/ex50.py create mode 100644 python/code/module-3/ex50_except.py create mode 100644 python/code/module-3/ex50_test.py create mode 100644 python/code/module-3/fake_input.py create mode 100644 python/code/module-3/languages.txt create mode 100644 python/code/module-3/lexicon_tests.py create mode 100644 python/code/module-3/mystuff.py create mode 100644 python/code/module-3/new_file.txt create mode 100644 python/code/module-3/setup.py create mode 100644 python/code/module-3/test.txt create mode 100644 python/code/module-3/tests/__init__.py create mode 100644 python/code/module-3/tests/ex47_tests.py create mode 100644 python/code/module-4/euro_migrate.sql create mode 100644 python/code/module-4/ex51.py create mode 100644 python/code/module-4/ex51_clue.py create mode 100644 python/code/module-4/ex52.py create mode 100644 python/code/module-4/ex53.py create mode 100644 python/code/module-4/ex54.py create mode 100644 python/code/module-4/ex57.py create mode 100644 python/code/module-4/ex58.py create mode 100644 python/code/module-4/ex62.py diff --git a/.gitignore b/.gitignore index ec2481e..08a09f0 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,4 @@ tags # Persistent undo [._]*.un~ +*.pyc diff --git a/python/code/module-1/ex1.err b/python/code/module-1/ex1.err new file mode 100644 index 0000000..24b9794 --- /dev/null +++ b/python/code/module-1/ex1.err @@ -0,0 +1,6 @@ +$ python3.6 python/ex1.py + File "python/ex1.py", line 3 + print("I like typing this. + ^ +SyntaxError: EOL while scanning string literal + diff --git a/python/code/module-1/ex1.py b/python/code/module-1/ex1.py new file mode 100644 index 0000000..6986148 --- /dev/null +++ b/python/code/module-1/ex1.py @@ -0,0 +1,7 @@ +print("Hello World!") +print("Hello Again") +print("I like typing this.") +print("This is fun.") +print('Yay! Printing.') +print("I'd much rather you 'not'.") +print('I "said" do not touch this.') diff --git a/python/code/module-1/ex10.py b/python/code/module-1/ex10.py new file mode 100644 index 0000000..1a02a14 --- /dev/null +++ b/python/code/module-1/ex10.py @@ -0,0 +1,15 @@ +tabby_cat = "\tI'm tabbed in." +persian_cat = "I'm split\non a line." +backslash_cat = "I'm \\ a \\ cat." + +fat_cat = """ +I'll do a list: +\t* Cat food +\t* Fishies +\t* Catnip\n\t* Grass +""" + +print(tabby_cat) +print(persian_cat) +print(backslash_cat) +print(fat_cat) diff --git a/python/code/module-1/ex11.py b/python/code/module-1/ex11.py new file mode 100644 index 0000000..e2aa9bd --- /dev/null +++ b/python/code/module-1/ex11.py @@ -0,0 +1,14 @@ +### @export "fake" +import fake_input +input, input = fake_input.create(['38', '6\'2"', '180lbs']) + +### @export "code" +print("How old are you?", end=' ') +age = input() +print("How tall are you?", end=' ') +height = input() +print("How much do you weigh?", end=' ') +weight = input() + +print(f"So, you're {age} old, {height} tall and {weight} heavy.") + diff --git a/python/code/module-1/ex12.py b/python/code/module-1/ex12.py new file mode 100644 index 0000000..d239f17 --- /dev/null +++ b/python/code/module-1/ex12.py @@ -0,0 +1,11 @@ +### @export "fake" +import fake_input +input, input = fake_input.create(['38', '6\'2"', '180lbs']) + +### @export "code" +age = input("How old are you? ") +height = input("How tall are you? ") +weight = input("How much do you weigh? ") + +print(f"So, you're {age} old, {height} tall and {weight} heavy.") + diff --git a/python/code/module-1/ex13.py b/python/code/module-1/ex13.py new file mode 100644 index 0000000..7d141c1 --- /dev/null +++ b/python/code/module-1/ex13.py @@ -0,0 +1,9 @@ +from sys import argv +# read the WYSS section for how to run this +script, first, second, third = argv + +print("The script is called:", script) +print("Your first variable is:", first) +print("Your second variable is:", second) +print("Your third variable is:", third) + diff --git a/python/code/module-1/ex14.py b/python/code/module-1/ex14.py new file mode 100644 index 0000000..cdf162d --- /dev/null +++ b/python/code/module-1/ex14.py @@ -0,0 +1,29 @@ +### @export "setup" +import fake_input +input, input = fake_input.create(['Yes', + "San Francisco", + 'Tandy 1000']) + +### @export "code" +from sys import argv + +script, user_name = argv +prompt = '> ' + +print(f"Hi {user_name}, I'm the {script} script.") +print("I'd like to ask you a few questions.") +print(f"Do you like me {user_name}?") +likes = input(prompt) + +print(f"Where do you live {user_name}?") +lives = input(prompt) + +print("What kind of computer do you have?") +computer = input(prompt) + +print(f""" +Alright, so you said {likes} about liking me. +You live in {lives}. Not sure where that is. +And you have a {computer} computer. Nice. +""") + diff --git a/python/code/module-1/ex15.py b/python/code/module-1/ex15.py new file mode 100644 index 0000000..51c7db6 --- /dev/null +++ b/python/code/module-1/ex15.py @@ -0,0 +1,22 @@ +### @export "setup" +import fake_input +input, input = fake_input.create(['ex15_sample.txt']) + +### @export "code" +from sys import argv + +script, filename = argv + +txt = open(filename) + +print(f"Here's your file {filename}:") +print(txt.read()) + +print("Type the filename again:") +file_again = input("> ") + +txt_again = open(file_again) + +print(txt_again.read()) + + diff --git a/python/code/module-1/ex15_sample.txt b/python/code/module-1/ex15_sample.txt new file mode 100644 index 0000000..6ab0e5c --- /dev/null +++ b/python/code/module-1/ex15_sample.txt @@ -0,0 +1,4 @@ +This is stuff I typed into a file. +It is really cool stuff. +Lots and lots of fun to have in here. + diff --git a/python/code/module-1/ex16.py b/python/code/module-1/ex16.py new file mode 100644 index 0000000..67660d2 --- /dev/null +++ b/python/code/module-1/ex16.py @@ -0,0 +1,38 @@ +### @export "setup" +import fake_input +input, input = fake_input.create(['', 'Mary had a little lamb', + 'Its fleece was white as snow', + 'It was also tasty']) + +### @export "code" +filename = "test.txt" + +print(f"We're going to erase {filename}.") +print("If you don't want that, hit CTRL-C (^C).") +print("If you do want that, hit RETURN.") + +input("?") + +print("Opening the file...") +target = open(filename, 'w') + +print("Truncating the file. Goodbye!") +target.truncate() + +print("Now I'm going to ask you for three lines.") + +line1 = input("line 1: ") +line2 = input("line 2: ") +line3 = input("line 3: ") + +print("I'm going to write these to the file.") + +target.write(line1) +target.write("\n") +target.write(line2) +target.write("\n") +target.write(line3) +target.write("\n") + +print("And finally, we close it.") +target.close() diff --git a/python/code/module-1/ex17.py b/python/code/module-1/ex17.py new file mode 100644 index 0000000..0bcfea5 --- /dev/null +++ b/python/code/module-1/ex17.py @@ -0,0 +1,29 @@ +### @export "fake" +import fake_input +input, input = fake_input.create(['']) + +### @export "code" +from os.path import exists + +from_file = "test.txt" +to_file = "new_test.txt" + +print(f"Copying from {from_file} to {to_file}") + +# we could do these two on one line, how? +in_file = open(from_file) +indata = in_file.read() + +print(f"The input file is {len(indata)} bytes long") + +print(f"Does the output file exist? {exists(to_file)}") +print("Ready, hit RETURN to continue, CTRL-C to abort.") +input() + +out_file = open(to_file, 'w') +out_file.write(indata) + +print("Alright, all done.") + +out_file.close() +in_file.close() diff --git a/python/code/module-1/ex2.py b/python/code/module-1/ex2.py new file mode 100644 index 0000000..bdbe0e8 --- /dev/null +++ b/python/code/module-1/ex2.py @@ -0,0 +1,10 @@ +# A comment, this is so you can read your program later. +# Anything after the # is ignored by python. + +print("I could have code like this.") # and the comment after is ignored + +# You can also use a comment to "disable" or comment out code: +# print("This won't run.") + +print("This will run.") + diff --git a/python/code/module-1/ex3.py b/python/code/module-1/ex3.py new file mode 100644 index 0000000..55ad89e --- /dev/null +++ b/python/code/module-1/ex3.py @@ -0,0 +1,23 @@ +print("I will now count my chickens:") + +print("Hens", 25 + 30 / 6) +print("Roosters", 100 - 25 * 3 % 7) + +print("Now I will count the eggs:") + +print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) + +print("Is it true that 3 + 2 < 5 - 7?") + +print(3 + 2 < 5 - 7) + +print("What is 3 + 2?", 3 + 2) +print("What is 5 - 7?", 5 - 7) + +print("Oh, that's why it's False.") + +print("How about some more.") + +print("Is it greater?", 5 > -2) +print("Is it greater or equal?", 5 >= -2) +print("Is it less or equal?", 5 <= -2) diff --git a/python/code/module-1/ex4.err b/python/code/module-1/ex4.err new file mode 100644 index 0000000..8845a5b --- /dev/null +++ b/python/code/module-1/ex4.err @@ -0,0 +1,4 @@ +Traceback (most recent call last): + File "ex4.py", line 8, in + average_passengers_per_car = car_pool_capacity / passenger +NameError: name 'car_pool_capacity' is not defined diff --git a/python/code/module-1/ex4.py b/python/code/module-1/ex4.py new file mode 100644 index 0000000..db07afb --- /dev/null +++ b/python/code/module-1/ex4.py @@ -0,0 +1,18 @@ +cars = 100 +space_in_a_car = 4.0 +drivers = 30 +passengers = 90 +cars_not_driven = cars - drivers +cars_driven = drivers +carpool_capacity = cars_driven * space_in_a_car +average_passengers_per_car = passengers / cars_driven + + +print("There are", cars, "cars available.") +print("There are only", drivers, "drivers available.") +print("There will be", cars_not_driven, "empty cars today.") +print("We can transport", carpool_capacity, "people today.") +print("We have", passengers, "to carpool today.") +print("We need to put about", average_passengers_per_car, + "in each car.") + diff --git a/python/code/module-1/ex5.py b/python/code/module-1/ex5.py new file mode 100644 index 0000000..3d5c805 --- /dev/null +++ b/python/code/module-1/ex5.py @@ -0,0 +1,19 @@ +my_name = 'Zed A. Shaw' +my_age = 35 # not a lie +my_height = 74 # inches +my_weight = 180 # lbs +my_eyes = 'Blue' +my_teeth = 'White' +my_hair = 'Brown' + +print(f"Let's talk about {my_name}.") +print(f"He's {my_height} inches tall.") +print(f"He's {my_weight} pounds heavy.") +print("Actually that's not too heavy.") +print(f"He's got {my_eyes} eyes and {my_hair} hair.") +print(f"His teeth are usually {my_teeth} depending on the coffee.") + +# this line is tricky, try to get it exactly right +total = my_age + my_height + my_weight +print(f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.") + diff --git a/python/code/module-1/ex6.py b/python/code/module-1/ex6.py new file mode 100644 index 0000000..b850e43 --- /dev/null +++ b/python/code/module-1/ex6.py @@ -0,0 +1,22 @@ +types_of_people = 10 +x = f"There are {types_of_people} types of people." + +binary = "binary" +do_not = "don't" +y = f"Those who know {binary} and those who {do_not}." + +print(x) +print(y) + +print(f"I said: {x}") +print(f"I also said: '{y}'") + +hilarious = False +joke_evaluation = "Isn't that joke so funny?! {}" + +print(joke_evaluation.format(hilarious)) + +w = "This is the left side of..." +e = "a string with a right side." + +print(w + e) diff --git a/python/code/module-1/ex7.py b/python/code/module-1/ex7.py new file mode 100644 index 0000000..ba7cb21 --- /dev/null +++ b/python/code/module-1/ex7.py @@ -0,0 +1,21 @@ +print("Mary had a little lamb.") +print("Its fleece was white as {}.".format('snow')) +print("And everywhere that Mary went.") +print("." * 10) # what'd that do? + +end1 = "C" +end2 = "h" +end3 = "e" +end4 = "e" +end5 = "s" +end6 = "e" +end7 = "B" +end8 = "u" +end9 = "r" +end10 = "g" +end11 = "e" +end12 = "r" + +# watch end = ' ' at the end. try removing it to see what happens +print(end1 + end2 + end3 + end4 + end5 + end6, end=' ') +print(end7 + end8 + end9 + end10 + end11 + end12) diff --git a/python/code/module-1/ex8.py b/python/code/module-1/ex8.py new file mode 100644 index 0000000..a893bb9 --- /dev/null +++ b/python/code/module-1/ex8.py @@ -0,0 +1,13 @@ +formatter = "{} {} {} {}" + +print(formatter.format(1, 2, 3, 4)) +print(formatter.format("one", "two", "three", "four")) +print(formatter.format(True, False, False, True)) +print(formatter.format(formatter, formatter, formatter, formatter)) +print(formatter.format( + "Try your", + "Own text here", + "Maybe a poem", + "Or a song about fear" +)) + diff --git a/python/code/module-1/ex9.py b/python/code/module-1/ex9.py new file mode 100644 index 0000000..1f57608 --- /dev/null +++ b/python/code/module-1/ex9.py @@ -0,0 +1,14 @@ +# Here's some new strange stuff, remember to type it exactly. + +days = "Mon Tue Wed Thu Fri Sat Sun" +months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" + +print("Here are the days: ", days) +print("Here are the months: ", months) + +print(""" +There's something going on here. +With the three double-quotes. +We'll be able to type as much as we like. +Even 4 lines if we want, or 5, or 6. +""") diff --git a/python/code/module-1/fake_input.py b/python/code/module-1/fake_input.py new file mode 100644 index 0000000..dbd4ace --- /dev/null +++ b/python/code/module-1/fake_input.py @@ -0,0 +1,13 @@ +def create(replies): + """Used for faking out scripts so they can run like + the book needs but be sectioned to appear to be normal. + """ + + def input(prompt=None): + reply = replies.pop(0) + if prompt: print(prompt, end=' ') + print(reply) + return reply + + return input, input + diff --git a/python/code/module-1/new_file.txt b/python/code/module-1/new_file.txt new file mode 100644 index 0000000..e3188be --- /dev/null +++ b/python/code/module-1/new_file.txt @@ -0,0 +1,3 @@ +Mary had a little lamb +Its fleece was white as snow +It was also tasty diff --git a/python/code/module-1/new_test.txt b/python/code/module-1/new_test.txt new file mode 100644 index 0000000..e3188be --- /dev/null +++ b/python/code/module-1/new_test.txt @@ -0,0 +1,3 @@ +Mary had a little lamb +Its fleece was white as snow +It was also tasty diff --git a/python/code/module-1/test.txt b/python/code/module-1/test.txt new file mode 100644 index 0000000..e3188be --- /dev/null +++ b/python/code/module-1/test.txt @@ -0,0 +1,3 @@ +Mary had a little lamb +Its fleece was white as snow +It was also tasty diff --git a/python/code/module-2/ex18.py b/python/code/module-2/ex18.py new file mode 100644 index 0000000..8f928a6 --- /dev/null +++ b/python/code/module-2/ex18.py @@ -0,0 +1,25 @@ + +# this one is like your scripts with argv +def print_two(*args): + arg1, arg2 = args + print(f"arg1: {arg1}, arg2: {arg2}") + +# ok, that *args is actually pointless, we can just do this +def print_two_again(arg1, arg2): + print(f"arg1: {arg1}, arg2: {arg2}") + +# this just takes one argument +def print_one(arg1): + print(f"arg1: {arg1}") + +# this one takes no arguments +def print_none(): + print("I got nothin'.") + + +print_two("Zed","Shaw") +print_two_again("Zed","Shaw") +print_one("First!") +print_none() + + diff --git a/python/code/module-2/ex18_demo.py b/python/code/module-2/ex18_demo.py new file mode 100644 index 0000000..13dc3b6 --- /dev/null +++ b/python/code/module-2/ex18_demo.py @@ -0,0 +1,31 @@ +### @export "1" + +def do_nothing(): + pass + +### @export "2" + +def do_something(): + print("I did something!") + +### @export "3" + +def do_something(): + print("I did something!") + +# now we can call it by its name +do_something() + +### @export "4" + +def do_more_things(a, b): + print("A IS", a, "B IS", b) + +do_more_things("hello", 1) + +### @export "5" + +def do_more_things(a, b): + a = "hello" + b = 1 + print("A IS", a, "B IS", b) diff --git a/python/code/module-2/ex19.py b/python/code/module-2/ex19.py new file mode 100644 index 0000000..a39d171 --- /dev/null +++ b/python/code/module-2/ex19.py @@ -0,0 +1,26 @@ + +def cheese_and_crackers(cheese_count, boxes_of_crackers): + print(f"You have {cheese_count} cheeses!") + print(f"You have {boxes_of_crackers} boxes of crackers!") + print("Man that's enough for a party!") + print("Get a blanket.\n") + + +print("We can just give the function numbers directly:") +cheese_and_crackers(20, 30) + + +print("OR, we can use variables from our script:") +amount_of_cheese = 10 +amount_of_crackers = 50 + +cheese_and_crackers(amount_of_cheese, amount_of_crackers) + + +print("We can even do math inside too:") +cheese_and_crackers(10 + 20, 5 + 6) + + +print("And we can combine the two, variables and math:") +cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) + diff --git a/python/code/module-2/ex20.py b/python/code/module-2/ex20.py new file mode 100644 index 0000000..b598c9f --- /dev/null +++ b/python/code/module-2/ex20.py @@ -0,0 +1,33 @@ +from sys import argv + +input_file = "ex20_test.txt" + +def print_all(f): + print(f.read()) + +def rewind(f): + f.seek(0) + +def print_a_line(line_count, f): + print(line_count, f.readline()) + +current_file = open(input_file) + +print("First let's print the whole file:\n") + +print_all(current_file) + +print("Now let's rewind, kind of like a tape.") + +rewind(current_file) + +print("Let's print three lines:") + +current_line = 1 +print_a_line(current_line, current_file) + +current_line = current_line + 1 +print_a_line(current_line, current_file) + +current_line = current_line + 1 +print_a_line(current_line, current_file) diff --git a/python/code/module-2/ex20_test.txt b/python/code/module-2/ex20_test.txt new file mode 100644 index 0000000..e97bf0c --- /dev/null +++ b/python/code/module-2/ex20_test.txt @@ -0,0 +1,3 @@ +This is line 1 +This is line 2 +This is line 3 diff --git a/python/code/module-2/ex21.py b/python/code/module-2/ex21.py new file mode 100644 index 0000000..48f5103 --- /dev/null +++ b/python/code/module-2/ex21.py @@ -0,0 +1,36 @@ + +def add(a, b): + print(f"ADDING {a} + {b}") + return a + b + +def subtract(a, b): + print(f"SUBTRACTING {a} - {b}") + return a - b + +def multiply(a, b): + print(f"MULTIPLYING {a} * {b}") + return a * b + +def divide(a, b): + print(f"DIVIDING {a} / {b}") + return a / b + + +print("Let's do some math with just functions!") + +age = add(30, 5) +height = subtract(78, 4) +weight = multiply(90, 2) +iq = divide(100, 2) + +print(f"Age: {age}, Height: {height}, Weight: {weight}, IQ: {iq}") + + +# A puzzle for the extra credit, type it in anyway. +print("Here is a puzzle.") + +what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) + +print("That becomes: ", what, "Can you do it by hand?") + + diff --git a/python/code/module-2/ex22.py b/python/code/module-2/ex22.py new file mode 100644 index 0000000..2c84407 --- /dev/null +++ b/python/code/module-2/ex22.py @@ -0,0 +1,23 @@ +import sys +script, input_encoding, error = sys.argv + + +def main(language_file, encoding, errors): + line = language_file.readline() + + if line: + print_line(line, encoding, errors) + return main(language_file, encoding, errors) + + +def print_line(line, encoding, errors): + next_lang = line.strip() + raw_bytes = next_lang.encode(encoding, errors=errors) + cooked_string = raw_bytes.decode(encoding, errors=errors) + + print(raw_bytes, "<===>", cooked_string) + + +languages = open("languages.txt", encoding="utf-8") + +main(languages, input_encoding, error) diff --git a/python/code/module-2/ex23.py b/python/code/module-2/ex23.py new file mode 100644 index 0000000..41c2fc8 --- /dev/null +++ b/python/code/module-2/ex23.py @@ -0,0 +1,18 @@ +fruit = [ + ['Apples', 12, 'AAA'], ['Oranges', 1, 'B'], + ['Pears', 2, 'A'], ['Grapes', 14, 'UR']] + +cars = [ + ['Cadillac', ['Black', 'Big', 34500]], + ['Corvette', ['Red', 'Little', 1000000]], + ['Ford', ['Blue', 'Medium', 1234]], + ['BMW', ['White', 'Baby', 7890]] +] + +languages = [ + ['Python', ['Slow', ['Terrible', 'Mush']]], + ['JavaSCript', ['Moderate', ['Alright', 'Bizarre']]], + ['Perl6', ['Moderate', ['Fun', 'Weird']]], + ['C', ['Fast', ['Annoying', 'Dangerous']]], + ['Forth', ['Fast', ['Fun', 'Difficult']]], +] diff --git a/python/code/module-2/ex24.py b/python/code/module-2/ex24.py new file mode 100644 index 0000000..0e681d0 --- /dev/null +++ b/python/code/module-2/ex24.py @@ -0,0 +1,30 @@ +fruit = [ + {'kind': 'Apples', 'count': 12, 'rating': 'AAA'}, + {'kind': 'Oranges', 'count': 1, 'rating': 'B'}, + {'kind': 'Pears', 'count': 2, 'rating': 'A'}, + {'kind': 'Grapes', 'count': 14, 'rating': 'UR'} +]; + +cars = [ + {'type': 'Cadillac', 'color': 'Black', + 'size': 'Big', 'miles': 34500}, + {'type': 'Corvette', 'color': 'Red', + 'size': 'Little', 'miles': 1000000}, + {'type': 'Ford', 'color': 'Blue', + 'size': 'Medium', 'miles': 1234}, + {'type': 'BMW', 'color': 'White', + 'size': 'Baby', 'miles': 7890} +]; + +languages = [ + {'name': 'Python', 'speed': 'Slow', + 'opinion': ['Terrible', 'Mush']}, + {'name': 'JavaScript', 'speed': 'Moderate', + 'opinion': ['Alright', 'Bizarre']}, + {'name': 'Perl6', 'speed': 'Moderate', + 'opinion': ['Fun', 'Weird']}, + {'name': 'C', 'speed': 'Fast', + 'opinion': ['Annoying', 'Dangerous']}, + {'name': 'Forth', 'speed': 'Fast', + 'opinion': ['Fun', 'Difficult']}, +]; diff --git a/python/code/module-2/ex25.py b/python/code/module-2/ex25.py new file mode 100644 index 0000000..3e48913 --- /dev/null +++ b/python/code/module-2/ex25.py @@ -0,0 +1,38 @@ + +def break_words(stuff): + """This function will break up words for us.""" + words = stuff.split(' ') + return words + +def sort_words(words): + """Sorts the words.""" + return sorted(words) + +def print_first_word(words): + """Prints the first word after popping it off.""" + word = words.pop(0) + print(word) + +def print_last_word(words): + """Prints the last word after popping it off.""" + word = words.pop(-1) + print(word) + +def sort_sentence(sentence): + """Takes in a full sentence and returns the sorted words.""" + words = break_words(sentence) + return sort_words(words) + +def print_first_and_last(sentence): + """Prints the first and last words of the sentence.""" + words = break_words(sentence) + print_first_word(words) + print_last_word(words) + +def print_first_and_last_sorted(sentence): + """Sorts the words then prints the first and last one.""" + words = sort_sentence(sentence) + print_first_word(words) + print_last_word(words) + + diff --git a/python/code/module-2/ex25_pycon.py b/python/code/module-2/ex25_pycon.py new file mode 100644 index 0000000..aefee22 --- /dev/null +++ b/python/code/module-2/ex25_pycon.py @@ -0,0 +1,16 @@ +import ex25 +sentence = "All good things come to those who wait." +words = ex25.break_words(sentence) +words +sorted_words = ex25.sort_words(words) +sorted_words +ex25.print_first_word(words) +ex25.print_last_word(words) +words +ex25.print_first_word(sorted_words) +ex25.print_last_word(sorted_words) +sorted_words +sorted_words = ex25.sort_sentence(sentence) +sorted_words +ex25.print_first_and_last(sentence) +ex25.print_first_and_last_sorted(sentence) diff --git a/python/code/module-2/ex26.py b/python/code/module-2/ex26.py new file mode 100644 index 0000000..bfda970 --- /dev/null +++ b/python/code/module-2/ex26.py @@ -0,0 +1,2 @@ +name = "Zed" +height = 74 diff --git a/python/code/module-2/ex26_code.py b/python/code/module-2/ex26_code.py new file mode 100644 index 0000000..0246e79 --- /dev/null +++ b/python/code/module-2/ex26_code.py @@ -0,0 +1,31 @@ +### @export "import" +import ex26 + +### @export "step1" +print("name", ex26.name) +print("height", ex26.height) + +### @export "step2a" +from pprint import pprint + +pprint(ex26.__dict__) + +### @export "step2b" +print("height is", ex26.height) +print("height is also", ex26.__dict__['height']) + +### @export "step3" +print(f"I am currently {ex26.height} inches tall.") + +ex26.__dict__['height'] = 1000 +print(f"I am now {ex26.height} inches tall.") + +ex26.height = 12 +print(f"Oops, now I'm {ex26.__dict__['height']} inches tall.") + +### @export "step4a" +from pprint import pprint +print(pprint.__doc__) + +### @export "step4b" +help(pprint) diff --git a/python/code/module-2/ex28.py b/python/code/module-2/ex28.py new file mode 100644 index 0000000..9e42102 --- /dev/null +++ b/python/code/module-2/ex28.py @@ -0,0 +1 @@ +# empty exercise diff --git a/python/code/module-2/ex30.py b/python/code/module-2/ex30.py new file mode 100644 index 0000000..e0a8a09 --- /dev/null +++ b/python/code/module-2/ex30.py @@ -0,0 +1,31 @@ + +people = 20 +cats = 30 +dogs = 15 + + +if people < cats: + print("Too many cats! The world is doomed!") + +if people > cats: + print("Not many cats! The world is saved!") + +if people < dogs: + print("The world is drooled on!") + +if people > dogs: + print("The world is dry!") + + +dogs += 5 + +if people >= dogs: + print("People are greater than or equal to dogs.") + +if people <= dogs: + print("People are less than or equal to dogs.") + + +if people == dogs: + print("People are dogs.") + diff --git a/python/code/module-2/ex31.py b/python/code/module-2/ex31.py new file mode 100644 index 0000000..3ddfd7a --- /dev/null +++ b/python/code/module-2/ex31.py @@ -0,0 +1,27 @@ + +people = 30 +cars = 40 +trucks = 15 + + +if cars > people: + print("We should take the cars.") +elif cars < people: + print("We should not take the cars.") +else: + print("We can't decide.") + +if trucks > cars: + print("That's too many trucks.") +elif trucks < cars: + print("Maybe we could take the trucks.") +else: + print("We still can't decide.") + +if people > trucks: + print("Alright, let's just take the trucks.") +else: + print("Fine, let's stay home then.") + + + diff --git a/python/code/module-2/ex32.py b/python/code/module-2/ex32.py new file mode 100644 index 0000000..5ad09cf --- /dev/null +++ b/python/code/module-2/ex32.py @@ -0,0 +1,49 @@ +### @export "fake" +import fake_input +input, input = fake_input.create([ + '1', + '2', + '']) + +### @export "code" + +print("""You enter a dark room with two doors. +Do you go through door #1 or door #2?""") + +door = input("> ") + +if door == "1": + print("There's a giant bear here eating a cheese cake.") + print("What do you do?") + print("1. Take the cake.") + print("2. Scream at the bear.") + + bear = input("> ") + + if bear == "1": + print("The bear eats your face off. Good job!") + elif bear == "2": + print("The bear eats your legs off. Good job!") + else: + print(f"Well, doing {bear} is probably better.") + print("Bear runs away.") + +elif door == "2": + print("You stare into the endless abyss at Cthulhu's retina.") + print("1. Blueberries.") + print("2. Yellow jacket clothespins.") + print("3. Understanding revolvers yelling melodies.") + + insanity = input("> ") + + if insanity == "1" or insanity == "2": + print("Your body survives powered by a mind of jello.") + print("Good job!") + else: + print("The insanity rots your eyes into a pool of muck.") + print("Good job!") + +else: + print("You stumble around and fall on a knife and die. Good job!") + + diff --git a/python/code/module-2/ex32_dis.py b/python/code/module-2/ex32_dis.py new file mode 100644 index 0000000..312c7cf --- /dev/null +++ b/python/code/module-2/ex32_dis.py @@ -0,0 +1,13 @@ +from dis import dis + +dis(''' +if door == "1": + print("1") + bear = input("> ") + if bear == "1": + print("bear 1") + elif bear == "2": + print("bear 2") + else: + print("bear 3") +''') diff --git a/python/code/module-2/ex33.py b/python/code/module-2/ex33.py new file mode 100644 index 0000000..0ea1e72 --- /dev/null +++ b/python/code/module-2/ex33.py @@ -0,0 +1,31 @@ + +the_count = [1, 2, 3, 4, 5] +fruits = ['apples', 'oranges', 'pears', 'apricots'] +change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] + +# this first kind of for-loop goes through a list +for number in the_count: + print(f"This is count {number}") + +# same as above +for fruit in fruits: + print(f"A fruit of type: {fruit}") + +# also we can go through mixed lists too +for i in change: + print(f"I got {i}") + +# we can also build lists, first start with an empty one +elements = [] + +# then use the range function to do 0 to 5 counts +for i in range(0, 6): + print(f"Adding {i} to the list.") + # append is a function that lists understand + elements.append(i) + +# now we can print them out too +for i in elements: + print(f"Element was: {i}") + + diff --git a/python/code/module-2/ex34.py b/python/code/module-2/ex34.py new file mode 100644 index 0000000..5d7a688 --- /dev/null +++ b/python/code/module-2/ex34.py @@ -0,0 +1,18 @@ +i = 0 +numbers = [] + +while i < 6: + print(f"At the top i is {i}") + numbers.append(i) + + i = i + 1 + print("Numbers now: ", numbers) + print(f"At the bottom i is {i}") + + +print("The numbers: ") + +for num in numbers: + print(num) + + diff --git a/python/code/module-2/ex35.py b/python/code/module-2/ex35.py new file mode 100644 index 0000000..a585ec6 --- /dev/null +++ b/python/code/module-2/ex35.py @@ -0,0 +1,87 @@ +### @export "fake" +import fake_input +input, input = fake_input.create([ + 'left', + 'taunt bear', + 'open door', + '1000' + '']) + +### @export "code" +from sys import exit + +def gold_room(): + print("This room is full of gold. How much do you take?") + + choice = input("> ") + if "0" in choice or "1" in choice: + how_much = int(choice) + else: + dead("Man, learn to type a number.") + + if how_much < 50: + print("Nice, you're not greedy, you win!") + exit(0) + else: + dead("You greedy bastard!") + + +def bear_room(): + print("There is a bear here.") + print("The bear has a bunch of honey.") + print("The fat bear is in front of another door.") + print("How are you going to move the bear?") + bear_moved = False + + while True: + choice = input("> ") + + if choice == "take honey": + dead("The bear looks at you then slaps your face off.") + elif choice == "taunt bear" and not bear_moved: + print("The bear has moved from the door.") + print("You can go through it now.") + bear_moved = True + elif choice == "taunt bear" and bear_moved: + dead("The bear gets pissed off and chews your leg off.") + elif choice == "open door" and bear_moved: + gold_room() + else: + print("I got no idea what that means.") + + +def cthulhu_room(): + print("Here you see the great evil Cthulhu.") + print("He, it, whatever stares at you and you go insane.") + print("Do you flee for your life or eat your head?") + + choice = input("> ") + + if "flee" in choice: + start() + elif "head" in choice: + dead("Well that was tasty!") + else: + cthulhu_room() + + +def dead(why): + print(why, "Good job!") + exit(0) + +def start(): + print("You are in a dark room.") + print("There is a door to your right and left.") + print("Which one do you take?") + + choice = input("> ") + + if choice == "left": + bear_room() + elif choice == "right": + cthulhu_room() + else: + dead("You stumble around the room until you starve.") + + +start() diff --git a/python/code/module-2/ex36.py b/python/code/module-2/ex36.py new file mode 100644 index 0000000..9e42102 --- /dev/null +++ b/python/code/module-2/ex36.py @@ -0,0 +1 @@ +# empty exercise diff --git a/python/code/module-2/ex37.py b/python/code/module-2/ex37.py new file mode 100644 index 0000000..9e42102 --- /dev/null +++ b/python/code/module-2/ex37.py @@ -0,0 +1 @@ +# empty exercise diff --git a/python/code/module-2/fake_input.py b/python/code/module-2/fake_input.py new file mode 100644 index 0000000..dbd4ace --- /dev/null +++ b/python/code/module-2/fake_input.py @@ -0,0 +1,13 @@ +def create(replies): + """Used for faking out scripts so they can run like + the book needs but be sectioned to appear to be normal. + """ + + def input(prompt=None): + reply = replies.pop(0) + if prompt: print(prompt, end=' ') + print(reply) + return reply + + return input, input + diff --git a/python/code/module-2/languages.txt b/python/code/module-2/languages.txt new file mode 100644 index 0000000..6d47317 --- /dev/null +++ b/python/code/module-2/languages.txt @@ -0,0 +1,97 @@ +Afrikaans +አማርኛ +Аҧсшәа +العربية +Aragonés +Arpetan +Azərbaycanca +Bamanankan +বাংলা +Bân-lâm-gú +Беларуская +Български +Boarisch +Bosanski +Буряад +Català +Чӑвашла +Čeština +Cymraeg +Dansk +Deutsch +Eesti +Ελληνικά +Español +Esperanto +فارسی +Français +Frysk +Gaelg +Gàidhlig +Galego +한국어 +Հայերեն +हिन्दी +Hrvatski +Ido +Interlingua +Italiano +עברית +ಕನ್ನಡ +Kapampangan +ქართული +Қазақша +Kreyòl ayisyen +Latgaļu +Latina +Latviešu +Lëtzebuergesch +Lietuvių +Magyar +Македонски +Malti +मराठी +მარგალური +مازِرونی +Bahasa Melayu +Монгол +Nederlands +नेपाल भाषा +日本語 +Norsk bokmål +Nouormand +Occitan +Oʻzbekcha/ўзбекча +ਪੰਜਾਬੀ +پنجابی +پښتو +Plattdüütsch +Polski +Português +Română +Romani +Русский +Seeltersk +Shqip +Simple English +Slovenčina +کوردیی ناوەندی +Српски / srpski +Suomi +Svenska +Tagalog +தமிழ் +ภาษาไทย +Taqbaylit +Татарча/tatarça +తెలుగు +Тоҷикӣ +Türkçe +Українська +اردو +Tiếng Việt +Võro +文言 +吴语 +ייִדיש +中文 diff --git a/python/code/module-3/ex38.py b/python/code/module-3/ex38.py new file mode 100644 index 0000000..5b08d7e --- /dev/null +++ b/python/code/module-3/ex38.py @@ -0,0 +1,25 @@ +ten_things = "Apples Oranges Crows Telephone Light Sugar" + +print("Wait there are not 10 things in that list. Let's fix that.") + +stuff = ten_things.split(' ') +more_stuff = ["Day", "Night", "Song", "Frisbee", + "Corn", "Banana", "Girl", "Boy"] + +while len(stuff) != 10: + next_one = more_stuff.pop() + print("Adding: ", next_one) + stuff.append(next_one) + print(f"There are {len(stuff)} items now.") + +print("There we go: ", stuff) + +print("Let's do some things with stuff.") + +print(stuff[1]) +print(stuff[-1]) # whoa! fancy +print(stuff.pop()) +print(' '.join(stuff)) # what? cool! +print('#'.join(stuff[3:5])) # super stellar! + + diff --git a/python/code/module-3/ex39.py b/python/code/module-3/ex39.py new file mode 100644 index 0000000..7587b9d --- /dev/null +++ b/python/code/module-3/ex39.py @@ -0,0 +1,62 @@ +# create a mapping of state to abbreviation +states = { + 'Oregon': 'OR', + 'Florida': 'FL', + 'California': 'CA', + 'New York': 'NY', + 'Michigan': 'MI' +} + +# create a basic set of states and some cities in them +cities = { + 'CA': 'San Francisco', + 'MI': 'Detroit', + 'FL': 'Jacksonville' +} + +# add some more cities +cities['NY'] = 'New York' +cities['OR'] = 'Portland' + +# print out some cities +print('-' * 10) +print("NY State has: ", cities['NY']) +print("OR State has: ", cities['OR']) + +# print some states +print('-' * 10) +print("Michigan's abbreviation is: ", states['Michigan']) +print("Florida's abbreviation is: ", states['Florida']) + +# do it by using the state then cities dict +print('-' * 10) +print("Michigan has: ", cities[states['Michigan']]) +print("Florida has: ", cities[states['Florida']]) + +# print every state abbreviation +print('-' * 10) +for state, abbrev in list(states.items()): + print(f"{state} is abbreviated {abbrev}") + +# print every city in state +print('-' * 10) +for abbrev, city in list(cities.items()): + print(f"{abbrev} has the city {city}") + +# now do both at the same time +print('-' * 10) +for state, abbrev in list(states.items()): + print(f"{state} state is abbreviated {abbrev}") + print(f"and has city {cities[abbrev]}") + +print('-' * 10) +# safely get a abbreviation by state that might not be there +state = states.get('Texas') + +if not state: + print("Sorry, no Texas.") + +# get a city with a default value +city = cities.get('TX', 'Does Not Exist') +print(f"The city for the state 'TX' is: {city}") + diff --git a/python/code/module-3/ex39_pycon.py b/python/code/module-3/ex39_pycon.py new file mode 100644 index 0000000..26a25d2 --- /dev/null +++ b/python/code/module-3/ex39_pycon.py @@ -0,0 +1,23 @@ +### @export "first" +things = ['a', 'b', 'c', 'd'] +print(things[1]) +things[1] = 'z' +print(things[1]) +things +### @export "second" +stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2} +print(stuff['name']) +print(stuff['age']) +print(stuff['height']) +stuff['city'] = "SF" +print(stuff['city']) +### @export "third" +stuff[1] = "Wow" +stuff[2] = "Neato" +print(stuff[1]) +print(stuff[2]) +### @export "fourth" +stuff.pop('city') +stuff.pop(1) +stuff.pop(2) +stuff diff --git a/python/code/module-3/ex40.py b/python/code/module-3/ex40.py new file mode 100644 index 0000000..bb44bb1 --- /dev/null +++ b/python/code/module-3/ex40.py @@ -0,0 +1,21 @@ + +class Song(object): + + def __init__(self, lyrics): + self.lyrics = lyrics + + def sing_me_a_song(self): + for line in self.lyrics: + print(line) + +happy_bday = Song(["Happy birthday to you", + "I don't want to get sued", + "So I'll stop right there"]) + +bulls_on_parade = Song(["They rally around tha family", + "With pockets full of shells"]) + +happy_bday.sing_me_a_song() + +bulls_on_parade.sing_me_a_song() + diff --git a/python/code/module-3/ex40a.py b/python/code/module-3/ex40a.py new file mode 100644 index 0000000..04b1378 --- /dev/null +++ b/python/code/module-3/ex40a.py @@ -0,0 +1,68 @@ +### @export "part0" + +mystuff = {'apple': "I AM APPLES!"} +print(mystuff['apple']) + +### @export "part1" + +# this goes in mystuff.py +def apple(): + print("I AM APPLES!") + +### @export "part2" + +import mystuff +mystuff.apple() + +### @export "part3" + +def apple(): + print("I AM APPLES!") + +# this is just a variable +tangerine = "Living reflection of a dream" + +### @export "part4" + +import mystuff + +mystuff.apple() +print(mystuff.tangerine) + +### @export "part5" + +mystuff['apple'] # get apple from dict +mystuff.apple() # get apple from the module +mystuff.tangerine # same thing, it's just a variable + +### @export "part6" + +class MyStuff(object): + + def __init__(self): + self.tangerine = "And now a thousand years between" + + def apple(self): + print("I AM CLASSY APPLES!") + + +### @export "part7" + +thing = MyStuff() +thing.apple() +print(thing.tangerine) + +### @export "part8" + +# dict style +mystuff['apples'] + +# module style +mystuff.apples() +print(mystuff.tangerine) + +# class style +thing = MyStuff() +thing.apples() +print(thing.tangerine) + diff --git a/python/code/module-3/ex41.py b/python/code/module-3/ex41.py new file mode 100644 index 0000000..97ca7bb --- /dev/null +++ b/python/code/module-3/ex41.py @@ -0,0 +1,3 @@ +from test_project import testing + +testing.hello() diff --git a/python/code/module-3/ex42.py b/python/code/module-3/ex42.py new file mode 100644 index 0000000..5b08d7e --- /dev/null +++ b/python/code/module-3/ex42.py @@ -0,0 +1,25 @@ +ten_things = "Apples Oranges Crows Telephone Light Sugar" + +print("Wait there are not 10 things in that list. Let's fix that.") + +stuff = ten_things.split(' ') +more_stuff = ["Day", "Night", "Song", "Frisbee", + "Corn", "Banana", "Girl", "Boy"] + +while len(stuff) != 10: + next_one = more_stuff.pop() + print("Adding: ", next_one) + stuff.append(next_one) + print(f"There are {len(stuff)} items now.") + +print("There we go: ", stuff) + +print("Let's do some things with stuff.") + +print(stuff[1]) +print(stuff[-1]) # whoa! fancy +print(stuff.pop()) +print(' '.join(stuff)) # what? cool! +print('#'.join(stuff[3:5])) # super stellar! + + diff --git a/python/code/module-3/ex42_demo.py b/python/code/module-3/ex42_demo.py new file mode 100644 index 0000000..f406fda --- /dev/null +++ b/python/code/module-3/ex42_demo.py @@ -0,0 +1,38 @@ +class TheThing(object): + + def __init__(self): + self.number = 0 + + def some_function(self): + print("I got called.") + + def add_me_up(self, more): + self.number += more + return self.number + +# two different things +a = TheThing() +b = TheThing() + +a.some_function() +b.some_function() + +print(a.add_me_up(20)) +print(b.add_me_up(30)) + +print(a.number) +print(b.number) + +# Study this. This is how you pass a variable +# from one class to another. You will need this. +class TheMultiplier(object): + + def __init__(self, base): + self.base = base + + def do_it(self, m): + return m * self.base + +x = TheMultiplier(a.number) +print(x.do_it(b.number)) + diff --git a/python/code/module-3/ex43.py b/python/code/module-3/ex43.py new file mode 100644 index 0000000..7587b9d --- /dev/null +++ b/python/code/module-3/ex43.py @@ -0,0 +1,62 @@ +# create a mapping of state to abbreviation +states = { + 'Oregon': 'OR', + 'Florida': 'FL', + 'California': 'CA', + 'New York': 'NY', + 'Michigan': 'MI' +} + +# create a basic set of states and some cities in them +cities = { + 'CA': 'San Francisco', + 'MI': 'Detroit', + 'FL': 'Jacksonville' +} + +# add some more cities +cities['NY'] = 'New York' +cities['OR'] = 'Portland' + +# print out some cities +print('-' * 10) +print("NY State has: ", cities['NY']) +print("OR State has: ", cities['OR']) + +# print some states +print('-' * 10) +print("Michigan's abbreviation is: ", states['Michigan']) +print("Florida's abbreviation is: ", states['Florida']) + +# do it by using the state then cities dict +print('-' * 10) +print("Michigan has: ", cities[states['Michigan']]) +print("Florida has: ", cities[states['Florida']]) + +# print every state abbreviation +print('-' * 10) +for state, abbrev in list(states.items()): + print(f"{state} is abbreviated {abbrev}") + +# print every city in state +print('-' * 10) +for abbrev, city in list(cities.items()): + print(f"{abbrev} has the city {city}") + +# now do both at the same time +print('-' * 10) +for state, abbrev in list(states.items()): + print(f"{state} state is abbreviated {abbrev}") + print(f"and has city {cities[abbrev]}") + +print('-' * 10) +# safely get a abbreviation by state that might not be there +state = states.get('Texas') + +if not state: + print("Sorry, no Texas.") + +# get a city with a default value +city = cities.get('TX', 'Does Not Exist') +print(f"The city for the state 'TX' is: {city}") + diff --git a/python/code/module-3/ex43_classes.py b/python/code/module-3/ex43_classes.py new file mode 100644 index 0000000..f7d3943 --- /dev/null +++ b/python/code/module-3/ex43_classes.py @@ -0,0 +1,57 @@ + +class Scene(object): + + def enter(self): + pass + + +class Engine(object): + + def __init__(self, scene_map): + pass + + def play(self): + pass + +class Death(Scene): + + def enter(self): + pass + +class CentralCorridor(Scene): + + def enter(self): + pass + +class LaserWeaponArmory(Scene): + + def enter(self): + pass + +class TheBridge(Scene): + + def enter(self): + pass + +class EscapePod(Scene): + + def enter(self): + pass + + +class Map(object): + + def __init__(self, start_scene): + pass + + def next_scene(self, scene_name): + pass + + def opening_scene(self): + pass + + +a_map = Map('central_corridor') +a_game = Engine(a_map) +a_game.play() + diff --git a/python/code/module-3/ex43_pycon.py b/python/code/module-3/ex43_pycon.py new file mode 100644 index 0000000..26a25d2 --- /dev/null +++ b/python/code/module-3/ex43_pycon.py @@ -0,0 +1,23 @@ +### @export "first" +things = ['a', 'b', 'c', 'd'] +print(things[1]) +things[1] = 'z' +print(things[1]) +things +### @export "second" +stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2} +print(stuff['name']) +print(stuff['age']) +print(stuff['height']) +stuff['city'] = "SF" +print(stuff['city']) +### @export "third" +stuff[1] = "Wow" +stuff[2] = "Neato" +print(stuff[1]) +print(stuff[2]) +### @export "fourth" +stuff.pop('city') +stuff.pop(1) +stuff.pop(2) +stuff diff --git a/python/code/module-3/ex43_pycon_out.py b/python/code/module-3/ex43_pycon_out.py new file mode 100644 index 0000000..77e8412 --- /dev/null +++ b/python/code/module-3/ex43_pycon_out.py @@ -0,0 +1,37 @@ +### @export "first" +>>> things = ['a', 'b', 'c', 'd'] +>>> print(things[1]) +b +>>> things[1] = 'z' +>>> print(things[1]) +z +>>> things +['a', 'z', 'c', 'd'] +### @export "second" +>>> stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2} +>>> print(stuff['name']) +Zed +>>> print(stuff['age']) +39 +>>> print(stuff['height']) +74 +>>> stuff['city'] = "SF" +>>> print(stuff['city']) +SF +### @export "third" +>>> stuff[1] = "Wow" +>>> stuff[2] = "Neato" +>>> print(stuff[1]) +Wow +>>> print(stuff[2]) +Neato +### @export "fourth" +>>> stuff.pop('city') +'SF' +>>> stuff.pop(1) +'Wow' +>>> stuff.pop(2) +'Neato' +>>> stuff +{'name': 'Zed', 'age': 39, 'height': 74} +>>> diff --git a/python/code/module-3/ex44_1.py b/python/code/module-3/ex44_1.py new file mode 100644 index 0000000..fd59066 --- /dev/null +++ b/python/code/module-3/ex44_1.py @@ -0,0 +1,10 @@ +becky = { + "name": "Becky", + "age": 34, + "eyes": "green" +} + +def talk(who, words): + print(f"I am {who['name']} and {words}") + +talk(becky, "I am talking here!") diff --git a/python/code/module-3/ex44_2.py b/python/code/module-3/ex44_2.py new file mode 100644 index 0000000..fc56c8f --- /dev/null +++ b/python/code/module-3/ex44_2.py @@ -0,0 +1,11 @@ +def talk(who, words): + print(f"I am {who['name']} and {words}") + +becky = { + "name": "Becky", + "age": 34, + "eyes": "green", + "talk": talk # see this? +} + +becky['talk'](becky, "I am talking here!") diff --git a/python/code/module-3/ex44_3.py b/python/code/module-3/ex44_3.py new file mode 100644 index 0000000..d214fd9 --- /dev/null +++ b/python/code/module-3/ex44_3.py @@ -0,0 +1,20 @@ +# this function makes functions +def constructor(color, size): + print(">>> constructor color:", color, "size:", size) + + # watch the indent! + def repeater(): + # notice this function is using color, size + print("### repeater color:", color, "size:", size) + + print("<<< exit constructor"); + return repeater + +# what's returned are repeater functions +blue_xl = constructor("blue", "xl") +green_sm = constructor("green", "sm") + +# see how these repeaters "know" the parameters? +for i in range(0,4): + blue_xl() + green_sm() diff --git a/python/code/module-3/ex44_4.py b/python/code/module-3/ex44_4.py new file mode 100644 index 0000000..e6dae37 --- /dev/null +++ b/python/code/module-3/ex44_4.py @@ -0,0 +1,17 @@ +def Person_new(name, age, eyes): + person = { + "name": name, + "age": age, + "eyes": eyes, + } + + def talk(words): + print(f"I am {person['name']} and {words}") + + person['talk'] = talk + + return person + +becky = Person_new("Becky", 39, "green") + +becky['talk']("I am talking here!") diff --git a/python/code/module-3/ex45.py b/python/code/module-3/ex45.py new file mode 100644 index 0000000..8103b90 --- /dev/null +++ b/python/code/module-3/ex45.py @@ -0,0 +1,13 @@ +class Person(object): + + # this is double underscores around init + def __init__(self, name, age, eyes): + self.name = name + self.age = age + self.eyes = eyes + + def talk(self, words): + print(f"I am {self.name} and {words}") + +becky = Person("Becky", 39, "green") +becky.talk("I am talking here!") diff --git a/python/code/module-3/ex46.py b/python/code/module-3/ex46.py new file mode 100644 index 0000000..7465bd2 --- /dev/null +++ b/python/code/module-3/ex46.py @@ -0,0 +1,78 @@ +## Animal is-a object (yes, sort of confusing) look at the extra credit +class Animal(object): + pass + +## ?? +class Dog(Animal): + + def __init__(self, name): + ## ?? + self.name = name + +## ?? +class Cat(Animal): + + def __init__(self, name): + ## ?? + self.name = name + +## ?? +class Person(object): + + def __init__(self, name): + ## ?? + self.name = name + + ## Person has-a pet of some kind + self.pet = None + +## ?? +class Employee(Person): + + def __init__(self, name, salary): + ## ?? hmm what is this strange magic? + super(Employee, self).__init__(name) + ## ?? + self.salary = salary + +## ?? +class Fish(object): + pass + +## ?? +class Salmon(Fish): + pass + +## ?? +class Halibut(Fish): + pass + + +## rover is-a Dog +rover = Dog("Rover") + +## ?? +satan = Cat("Satan") + +## ?? +mary = Person("Mary") + +## ?? +mary.pet = satan + +## ?? +frank = Employee("Frank", 120000) + +## ?? +frank.pet = rover + +## ?? +flipper = Fish() + +## ?? +crouse = Salmon() + +## ?? +harry = Halibut() + + diff --git a/python/code/module-3/ex47.py b/python/code/module-3/ex47.py new file mode 100644 index 0000000..1c4f5b3 --- /dev/null +++ b/python/code/module-3/ex47.py @@ -0,0 +1,180 @@ +### @export "fake" +import fake_input +input, input = fake_input.create(['dodge!']) + +### @export "imports" + +from sys import exit +from random import randint +from ex47_dialogue import DIALOGUE + +### @export "scene_class" + + +class Scene(object): + + def enter(self): + print("This scene is not yet configured.") + print("Subclass it and implement enter().") + exit(1) + +### @export "engine_class" + +class Engine(object): + + def __init__(self, scene_map): + self.scene_map = scene_map + + def play(self): + current_scene = self.scene_map.opening_scene() + last_scene = self.scene_map.next_scene('finished') + + while current_scene != last_scene: + next_scene_name = current_scene.enter() + current_scene = self.scene_map.next_scene(next_scene_name) + + # be sure to print out the last scene + current_scene.enter() + +### @export "death_scene" + +class Death(Scene): + + quips = [ + "You died. You kinda suck at this.", + "Your Mom would be proud...if she were smarter.", + "Such a luser.", + "I have a small puppy that's better at this.", + "You're worse than your Dad's jokes." + + ] + + def enter(self): + print(Death.quips[randint(0, len(self.quips)-1)]) + exit(1) + + +### @export "central_corridor" + +class CentralCorridor(Scene): + + def enter(self): + print(DIALOGUE["CentralCorridor_enter"]) + + action = input("> ") + + if action == "shoot!": + print(DIALOGUE["CentralCorridor_shoot"]) + return 'death' + + elif action == "dodge!": + print(DIALOGUE["CentralCorridor_dodge"]) + return 'death' + + elif action == "tell a joke": + print(DIALOGUE["CentralCorridor_joke"]) + return 'laser_weapon_armory' + + else: + print("DOES NOT COMPUTE!") + return 'central_corridor' + +### @export "game_scenes" + +class LaserWeaponArmory(Scene): + + def enter(self): + print(DIALOGUE["LaserWeaponArmory_enter"]) + + code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}" + guess = input("[keypad]> ") + guesses = 0 + + while guess != code and guesses < 10: + print("BZZZZEDDD!") + guesses += 1 + guess = input("[keypad]> ") + + if guess == code: + print(DIALOGUE["LaserWeaponArmory_guess"]) + return 'the_bridge' + else: + print(DIALOGUE["LaserWeaponArmory_fail"]) + return 'death' + + + +class TheBridge(Scene): + + def enter(self): + print(DIALOGUE["TheBridge_enter"]) + + action = input("> ") + + if action == "throw the bomb": + print(DIALOGUE["TheBridge_throw_bomb"]) + return 'death' + + elif action == "slowly place the bomb": + print(DIALOGUE["TheBridge_place_bomb"]) + + return 'escape_pod' + else: + print("DOES NOT COMPUTE!") + return "the_bridge" + + +class EscapePod(Scene): + + def enter(self): + print(DIALOGUE["EscapePod_enter"]) + + good_pod = randint(1,5) + guess = input("[pod #]> ") + + + if int(guess) != good_pod: + print(DIALOGUE["EscapePod_death"] + .format(guess=guess)) + return 'death' + else: + print(DIALOGUE["EscapePod_escape"] + .format(guess=guess)) + + return 'finished' + +class Finished(Scene): + + def enter(self): + print("You won! Good job.") + return 'finished' + + +### @export "map_class" + +class Map(object): + + scenes = { + 'central_corridor': CentralCorridor(), + 'laser_weapon_armory': LaserWeaponArmory(), + 'the_bridge': TheBridge(), + 'escape_pod': EscapePod(), + 'death': Death(), + 'finished': Finished(), + } + + def __init__(self, start_scene): + self.start_scene = start_scene + + def next_scene(self, scene_name): + val = Map.scenes.get(scene_name) + return val + + def opening_scene(self): + return self.next_scene(self.start_scene) + +### @export "final_run" + +a_map = Map('central_corridor') +a_game = Engine(a_map) +a_game.play() diff --git a/python/code/module-3/ex47.sh-session b/python/code/module-3/ex47.sh-session new file mode 100644 index 0000000..7b02258 --- /dev/null +++ b/python/code/module-3/ex47.sh-session @@ -0,0 +1,6 @@ +$ nosetests +... +---------------------------------------------------------------------- +Ran 3 tests in 0.008s + +OK diff --git a/python/code/module-3/ex47/__init__.py b/python/code/module-3/ex47/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/python/code/module-3/ex47/game.py b/python/code/module-3/ex47/game.py new file mode 100644 index 0000000..59021da --- /dev/null +++ b/python/code/module-3/ex47/game.py @@ -0,0 +1,16 @@ + + +class Room(object): + + def __init__(self, name, description): + self.name = name + self.description = description + self.paths = {} + + def go(self, direction): + return self.paths.get(direction, None) + + def add_paths(self, paths): + self.paths.update(paths) + + diff --git a/python/code/module-3/ex47_classes.py b/python/code/module-3/ex47_classes.py new file mode 100644 index 0000000..f7d3943 --- /dev/null +++ b/python/code/module-3/ex47_classes.py @@ -0,0 +1,57 @@ + +class Scene(object): + + def enter(self): + pass + + +class Engine(object): + + def __init__(self, scene_map): + pass + + def play(self): + pass + +class Death(Scene): + + def enter(self): + pass + +class CentralCorridor(Scene): + + def enter(self): + pass + +class LaserWeaponArmory(Scene): + + def enter(self): + pass + +class TheBridge(Scene): + + def enter(self): + pass + +class EscapePod(Scene): + + def enter(self): + pass + + +class Map(object): + + def __init__(self, start_scene): + pass + + def next_scene(self, scene_name): + pass + + def opening_scene(self): + pass + + +a_map = Map('central_corridor') +a_game = Engine(a_map) +a_game.play() + diff --git a/python/code/module-3/ex47_dialogue.py b/python/code/module-3/ex47_dialogue.py new file mode 100644 index 0000000..44fc919 --- /dev/null +++ b/python/code/module-3/ex47_dialogue.py @@ -0,0 +1,107 @@ +DIALOGUE = { + "CentralCorridor_enter": """ +The Gothons of Planet Percal #25 have invaded your ship and +destroyed your entire crew. You are the last surviving +member and your last mission is to get the neutron destruct +bomb from the Weapons Armory, put it in the bridge, and blow +the ship up after getting into an escape pod. + +You're running down the central corridor to the Weapons +Armory when a Gothon jumps out, red scaly skin, dark grimy +teeth, and evil clown costume flowing around his hate filled +body. He's blocking the door to the Armory and about to +pull a weapon to blast you. +""", +"CentralCorridor_shoot": """ +Quick on the draw you yank out your blaster and fire it at +the Gothon. His clown costume is flowing and moving around +his body, which throws off your aim. Your laser hits his +costume but misses him entirely. This completely ruins his +brand new costume his mother bought him, which makes him fly +into an insane rage and blast you repeatedly in the face +until you are dead. Then he eats you. +""", +"CentralCorridor_dodge": """ +Like a world class boxer you dodge, weave, slip and slide +right as the Gothon's blaster cranks a laser past your head. +In the middle of your artful dodge your foot slips and you +bang your head on the metal wall and pass out. You wake up +shortly after only to die as the Gothon stomps on your head +and eats you. +""", +"CentralCorridor_joke": """ +Lucky for you they made you learn Gothon insults in the +academy. You tell the one Gothon joke you know: Lbhe zbgure +vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq +gur ubhfr. The Gothon stops, tries not to laugh, then busts +out laughing and can't move. While he's laughing you run up +and shoot him square in the head putting him down, then jump +through the Weapon Armory door. +""", +"LaserWeaponArmory_enter": """ +You do a dive roll into the Weapon Armory, crouch and scan +the room for more Gothons that might be hiding. It's dead +quiet, too quiet. You stand up and run to the far side of +the room and find the neutron bomb in its container. +There's a keypad lock on the box and you need the code to +get the bomb out. If you get the code wrong 10 times then +the lock closes forever and you can't get the bomb. The +code is 3 digits. +""", +"LaserWeaponArmory_guess": """ +The container clicks open and the seal breaks, letting gas +out. You grab the neutron bomb and run as fast as you can +to the bridge where you must place it in the right spot. +""", +"LaserWeaponArmory_fail": """ +The lock buzzes one last time and then you hear a sickening +melting sound as the mechanism is fused together. You +decide to sit there, and finally the Gothons blow up the +ship from their ship and you die. +""", +"TheBridge_enter": """ +You burst onto the Bridge with the netron destruct bomb +under your arm and surprise 5 Gothons who are trying to take +control of the ship. Each of them has an even uglier clown +costume than the last. They haven't pulled their weapons +out yet, as they see the active bomb under your arm and +don't want to set it off. +""", +"TheBridge_throw_bomb": """ +In a panic you throw the bomb at the group of Gothons and +make a leap for the door. Right as you drop it a Gothon +shoots you right in the back killing you. As you die you +see another Gothon frantically try to disarm the bomb. You +die knowing they will probably blow up when it goes off. +""", +"TheBridge_place_bomb": """ +You point your blaster at the bomb under your arm and the +Gothons put their hands up and start to sweat. You inch +backward to the door, open it, and then carefully place the +bomb on the floor, pointing your blaster at it. You then +jump back through the door, punch the close button and blast +the lock so the Gothons can't get out. Now that the bomb is +placed you run to the escape pod to get off this tin can. +""", +"EscapePod_enter":""" +You rush through the ship desperately trying to make it to +the escape pod before the whole ship explodes. It seems +like hardly any Gothons are on the ship, so your run is +clear of interference. You get to the chamber with the +escape pods, and now need to pick one to take. Some of them +could be damaged but you don't have time to look. There's 5 +pods, which one do you take? +""", +"EscapePod_death":""" +You jump into pod {guess} and hit the eject button. The pod +escapes out into the void of space, then implodes as the +hull ruptures, crushing your body into jam jelly. +""", +"EscapePod_escape":""" +You jump into pod {guess} and hit the eject button. The pod +easily slides out into space heading to the planet below. +As it flies to the planet, you look back and see your ship +implode then explode like a bright star, taking out the +Gothon ship at the same time. You won! +""", +} diff --git a/python/code/module-3/ex47_tests.py b/python/code/module-3/ex47_tests.py new file mode 100644 index 0000000..b8cee1c --- /dev/null +++ b/python/code/module-3/ex47_tests.py @@ -0,0 +1,33 @@ +from nose.tools import * +from ex47.game import Room + + +def test_room(): + gold = Room("GoldRoom", + """This room has gold in it you can grab. There's a + door to the north.""") + assert_equal(gold.name, "GoldRoom") + assert_equal(gold.paths, {}) + +def test_room_paths(): + center = Room("Center", "Test room in the center.") + north = Room("North", "Test room in the north.") + south = Room("South", "Test room in the south.") + + center.add_paths({'north': north, 'south': south}) + assert_equal(center.go('north'), north) + assert_equal(center.go('south'), south) + +def test_map(): + start = Room("Start", "You can go west and down a hole.") + west = Room("Trees", "There are trees here, you can go east.") + down = Room("Dungeon", "It's dark down here, you can go up.") + + start.add_paths({'west': west, 'down': down}) + west.add_paths({'east': start}) + down.add_paths({'up': start}) + + assert_equal(start.go('west'), west) + assert_equal(start.go('west').go('east'), start) + assert_equal(start.go('down').go('up'), start) + diff --git a/python/code/module-3/ex48_convert.py b/python/code/module-3/ex48_convert.py new file mode 100644 index 0000000..bbaebcb --- /dev/null +++ b/python/code/module-3/ex48_convert.py @@ -0,0 +1,6 @@ +def convert_number(s): + try: + return int(s) + except ValueError: + return None + diff --git a/python/code/module-3/ex48_pycon.py b/python/code/module-3/ex48_pycon.py new file mode 100644 index 0000000..a9699fc --- /dev/null +++ b/python/code/module-3/ex48_pycon.py @@ -0,0 +1 @@ +int("hell") diff --git a/python/code/module-3/ex48a.py b/python/code/module-3/ex48a.py new file mode 100644 index 0000000..f43251b --- /dev/null +++ b/python/code/module-3/ex48a.py @@ -0,0 +1,13 @@ +class Parent(object): + + def implicit(self): + print("PARENT implicit()") + +class Child(Parent): + pass + +dad = Parent() +son = Child() + +dad.implicit() +son.implicit() diff --git a/python/code/module-3/ex48b.py b/python/code/module-3/ex48b.py new file mode 100644 index 0000000..6be9e7b --- /dev/null +++ b/python/code/module-3/ex48b.py @@ -0,0 +1,15 @@ +class Parent(object): + + def override(self): + print("PARENT override()") + +class Child(Parent): + + def override(self): + print("CHILD override()") + +dad = Parent() +son = Child() + +dad.override() +son.override() diff --git a/python/code/module-3/ex48c.py b/python/code/module-3/ex48c.py new file mode 100644 index 0000000..1bc3fc5 --- /dev/null +++ b/python/code/module-3/ex48c.py @@ -0,0 +1,17 @@ +class Parent(object): + + def altered(self): + print("PARENT altered()") + +class Child(Parent): + + def altered(self): + print("CHILD, BEFORE PARENT altered()") + super(Child, self).altered() + print("CHILD, AFTER PARENT altered()") + +dad = Parent() +son = Child() + +dad.altered() +son.altered() diff --git a/python/code/module-3/ex48d.py b/python/code/module-3/ex48d.py new file mode 100644 index 0000000..8dd2f92 --- /dev/null +++ b/python/code/module-3/ex48d.py @@ -0,0 +1,33 @@ +class Parent(object): + + def override(self): + print("PARENT override()") + + def implicit(self): + print("PARENT implicit()") + + def altered(self): + print("PARENT altered()") + +class Child(Parent): + + def override(self): + print("CHILD override()") + + def altered(self): + print("CHILD, BEFORE PARENT altered()") + super(Child, self).altered() + print("CHILD, AFTER PARENT altered()") + +dad = Parent() +son = Child() + +dad.implicit() +son.implicit() + +dad.override() +son.override() + +dad.altered() +son.altered() + diff --git a/python/code/module-3/ex48e.py b/python/code/module-3/ex48e.py new file mode 100644 index 0000000..93ed795 --- /dev/null +++ b/python/code/module-3/ex48e.py @@ -0,0 +1,32 @@ +class Other(object): + + def override(self): + print("OTHER override()") + + def implicit(self): + print("OTHER implicit()") + + def altered(self): + print("OTHER altered()") + +class Child(object): + + def __init__(self): + self.other = Other() + + def implicit(self): + self.other.implicit() + + def override(self): + print("CHILD override()") + + def altered(self): + print("CHILD, BEFORE OTHER altered()") + self.other.altered() + print("CHILD, AFTER OTHER altered()") + +son = Child() + +son.implicit() +son.override() +son.altered() diff --git a/python/code/module-3/ex49_pycon.py b/python/code/module-3/ex49_pycon.py new file mode 100644 index 0000000..a947430 --- /dev/null +++ b/python/code/module-3/ex49_pycon.py @@ -0,0 +1,4 @@ +from ex48 import lexicon +lexicon.scan("go north") +lexicon.scan("kill the princess") +lexicon.scan("eat the bear") diff --git a/python/code/module-3/ex49a_pycon.py b/python/code/module-3/ex49a_pycon.py new file mode 100644 index 0000000..8d4cb4c --- /dev/null +++ b/python/code/module-3/ex49a_pycon.py @@ -0,0 +1,10 @@ +from ex48.parser import * +x = parse_sentence([('verb', 'run'), ('direction', 'north')]) +x.subject +x.verb +x.object +x = parse_sentence([('noun', 'bear'), ('verb', 'eat'), ('stop', 'the'), + ('noun', 'honey')]) +x.subject +x.verb +x.object diff --git a/python/code/module-3/ex50.py b/python/code/module-3/ex50.py new file mode 100644 index 0000000..ff2f653 --- /dev/null +++ b/python/code/module-3/ex50.py @@ -0,0 +1,11 @@ +class Person: + def __init__(self, name, hp, damage): + self.name = name + self.hp = hp + self.damage = damage + + def hit(self, who): + who.hp -= self.damage + + def alive(self): + return self.hp > 0 diff --git a/python/code/module-3/ex50_except.py b/python/code/module-3/ex50_except.py new file mode 100644 index 0000000..abc546f --- /dev/null +++ b/python/code/module-3/ex50_except.py @@ -0,0 +1,9 @@ +try: + count = int("hello") +except ValueError: + print("Bad number given.") + +try: + assert 1 == 2, "One does not equal 2" +except Exception as what: + print("assert throws", type(what)) diff --git a/python/code/module-3/ex50_test.py b/python/code/module-3/ex50_test.py new file mode 100644 index 0000000..7ea3001 --- /dev/null +++ b/python/code/module-3/ex50_test.py @@ -0,0 +1,15 @@ +from ex50 import Person + +def test_combat(): + boxer = Person("Boxer", 100, 10) + zombie = Person("Zed", 1000, 1000) + + # these asserts are bad, fix them + assert boxer.hp == 100, "Boxer has wrong hp." + assert zombie.hp == 1000, "Zombe has wrong hp." + + boxer.hit(zombie) + assert zombie.alive(), "Zombie should be alive." + + zombie.hit(boxer) + assert not boxer.alive(), "Boxer should be dead." diff --git a/python/code/module-3/fake_input.py b/python/code/module-3/fake_input.py new file mode 100644 index 0000000..dbd4ace --- /dev/null +++ b/python/code/module-3/fake_input.py @@ -0,0 +1,13 @@ +def create(replies): + """Used for faking out scripts so they can run like + the book needs but be sectioned to appear to be normal. + """ + + def input(prompt=None): + reply = replies.pop(0) + if prompt: print(prompt, end=' ') + print(reply) + return reply + + return input, input + diff --git a/python/code/module-3/languages.txt b/python/code/module-3/languages.txt new file mode 100644 index 0000000..6d47317 --- /dev/null +++ b/python/code/module-3/languages.txt @@ -0,0 +1,97 @@ +Afrikaans +አማርኛ +Аҧсшәа +العربية +Aragonés +Arpetan +Azərbaycanca +Bamanankan +বাংলা +Bân-lâm-gú +Беларуская +Български +Boarisch +Bosanski +Буряад +Català +Чӑвашла +Čeština +Cymraeg +Dansk +Deutsch +Eesti +Ελληνικά +Español +Esperanto +فارسی +Français +Frysk +Gaelg +Gàidhlig +Galego +한국어 +Հայերեն +हिन्दी +Hrvatski +Ido +Interlingua +Italiano +עברית +ಕನ್ನಡ +Kapampangan +ქართული +Қазақша +Kreyòl ayisyen +Latgaļu +Latina +Latviešu +Lëtzebuergesch +Lietuvių +Magyar +Македонски +Malti +मराठी +მარგალური +مازِرونی +Bahasa Melayu +Монгол +Nederlands +नेपाल भाषा +日本語 +Norsk bokmål +Nouormand +Occitan +Oʻzbekcha/ўзбекча +ਪੰਜਾਬੀ +پنجابی +پښتو +Plattdüütsch +Polski +Português +Română +Romani +Русский +Seeltersk +Shqip +Simple English +Slovenčina +کوردیی ناوەندی +Српски / srpski +Suomi +Svenska +Tagalog +தமிழ் +ภาษาไทย +Taqbaylit +Татарча/tatarça +తెలుగు +Тоҷикӣ +Türkçe +Українська +اردو +Tiếng Việt +Võro +文言 +吴语 +ייִדיש +中文 diff --git a/python/code/module-3/lexicon_tests.py b/python/code/module-3/lexicon_tests.py new file mode 100644 index 0000000..ec79a04 --- /dev/null +++ b/python/code/module-3/lexicon_tests.py @@ -0,0 +1,49 @@ +from nose.tools import * +from ex48 import lexicon + + +def test_directions(): + assert_equal(lexicon.scan("north"), [('direction', 'north')]) + result = lexicon.scan("north south east") + assert_equal(result, [('direction', 'north'), + ('direction', 'south'), + ('direction', 'east')]) + +def test_verbs(): + assert_equal(lexicon.scan("go"), [('verb', 'go')]) + result = lexicon.scan("go kill eat") + assert_equal(result, [('verb', 'go'), + ('verb', 'kill'), + ('verb', 'eat')]) + + +def test_stops(): + assert_equal(lexicon.scan("the"), [('stop', 'the')]) + result = lexicon.scan("the in of") + assert_equal(result, [('stop', 'the'), + ('stop', 'in'), + ('stop', 'of')]) + + +def test_nouns(): + assert_equal(lexicon.scan("bear"), [('noun', 'bear')]) + result = lexicon.scan("bear princess") + assert_equal(result, [('noun', 'bear'), + ('noun', 'princess')]) + +def test_numbers(): + assert_equal(lexicon.scan("1234"), [('number', 1234)]) + result = lexicon.scan("3 91234") + assert_equal(result, [('number', 3), + ('number', 91234)]) + + +def test_errors(): + assert_equal(lexicon.scan("ASDFADFASDF"), + [('error', 'ASDFADFASDF')]) + result = lexicon.scan("bear IAS princess") + assert_equal(result, [('noun', 'bear'), + ('error', 'IAS'), + ('noun', 'princess')]) + + diff --git a/python/code/module-3/mystuff.py b/python/code/module-3/mystuff.py new file mode 100644 index 0000000..ea01a6a --- /dev/null +++ b/python/code/module-3/mystuff.py @@ -0,0 +1,2 @@ +def apple(): + print("I AM APPLES!") diff --git a/python/code/module-3/new_file.txt b/python/code/module-3/new_file.txt new file mode 100644 index 0000000..e3188be --- /dev/null +++ b/python/code/module-3/new_file.txt @@ -0,0 +1,3 @@ +Mary had a little lamb +Its fleece was white as snow +It was also tasty diff --git a/python/code/module-3/setup.py b/python/code/module-3/setup.py new file mode 100644 index 0000000..d46dca3 --- /dev/null +++ b/python/code/module-3/setup.py @@ -0,0 +1,20 @@ +try: + from setuptools import setup +except ImportError: + from distutils.core import setup + +config = { + 'description': 'My Project', + 'author': 'My Name', + 'url': 'URL to get it at.', + 'download_url': 'Where to download it.', + 'author_email': 'My email.', + 'version': '0.1', + 'install_requires': ['nose'], + 'packages': ['NAME'], + 'scripts': [], + 'name': 'projectname' +} + +setup(**config) + diff --git a/python/code/module-3/test.txt b/python/code/module-3/test.txt new file mode 100644 index 0000000..e3188be --- /dev/null +++ b/python/code/module-3/test.txt @@ -0,0 +1,3 @@ +Mary had a little lamb +Its fleece was white as snow +It was also tasty diff --git a/python/code/module-3/tests/__init__.py b/python/code/module-3/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/python/code/module-3/tests/ex47_tests.py b/python/code/module-3/tests/ex47_tests.py new file mode 100644 index 0000000..b8cee1c --- /dev/null +++ b/python/code/module-3/tests/ex47_tests.py @@ -0,0 +1,33 @@ +from nose.tools import * +from ex47.game import Room + + +def test_room(): + gold = Room("GoldRoom", + """This room has gold in it you can grab. There's a + door to the north.""") + assert_equal(gold.name, "GoldRoom") + assert_equal(gold.paths, {}) + +def test_room_paths(): + center = Room("Center", "Test room in the center.") + north = Room("North", "Test room in the north.") + south = Room("South", "Test room in the south.") + + center.add_paths({'north': north, 'south': south}) + assert_equal(center.go('north'), north) + assert_equal(center.go('south'), south) + +def test_map(): + start = Room("Start", "You can go west and down a hole.") + west = Room("Trees", "There are trees here, you can go east.") + down = Room("Dungeon", "It's dark down here, you can go up.") + + start.add_paths({'west': west, 'down': down}) + west.add_paths({'east': start}) + down.add_paths({'up': start}) + + assert_equal(start.go('west'), west) + assert_equal(start.go('west').go('east'), start) + assert_equal(start.go('down').go('up'), start) + diff --git a/python/code/module-4/euro_migrate.sql b/python/code/module-4/euro_migrate.sql new file mode 100644 index 0000000..51273e1 --- /dev/null +++ b/python/code/module-4/euro_migrate.sql @@ -0,0 +1,14 @@ +DROP TABLE IF EXISTS currency; + +CREATE TABLE currency (id INTEGER PRIMARY KEY + AUTOINCREMENT NOT NULL, currency TEXT); + +ALTER TABLE rate ADD COLUMN currency_id INTEGER; + +INSERT INTO currency (currency) SELECT currency FROM rate GROUP BY +currency; + +UPDATE rate SET currency_id = currency.id FROM currency WHERE +rate.currency = currency.currency; + +ALTER TABLE rate DROP COLUMN currency; diff --git a/python/code/module-4/ex51.py b/python/code/module-4/ex51.py new file mode 100644 index 0000000..8128eff --- /dev/null +++ b/python/code/module-4/ex51.py @@ -0,0 +1,19 @@ +# import modules I need +import pdftotext +import sys + +# open the pdf +infile = open(sys.argv[1], "rb") + +# convert it to text +pdf = pdftotext.PDF(infile) + +lines = "".join(pdf).split("\n") + +# find Reporting Period +for line in lines: + if line.startswith("Reporting Period"): + # print it + print(line) + else: + print(line) diff --git a/python/code/module-4/ex51_clue.py b/python/code/module-4/ex51_clue.py new file mode 100644 index 0000000..3b1f45b --- /dev/null +++ b/python/code/module-4/ex51_clue.py @@ -0,0 +1,28 @@ +import pdftotext +import sys +import re + +# Load your PDF +with open(sys.argv[1], "rb") as f: + pdf = pdftotext.PDF(f) + + assert len(pdf) == 1, "This report is more than 1 page!" + + lines = "".join(pdf).split("\n") + +numbers = re.compile(r"^[,\d\s]+$") +ignore = re.compile(r"^\s*$") + +for line in lines: + if line == "\x0c" or ignore.match(line): + # ignore blank lines and trailing junk + continue + elif numbers.match(line): + # it's a number + try: + n = int(line.replace(',','')) + print(n) + except: + print("BAD", repr(line)); + else: + print("TEXT", line) diff --git a/python/code/module-4/ex52.py b/python/code/module-4/ex52.py new file mode 100644 index 0000000..87da201 --- /dev/null +++ b/python/code/module-4/ex52.py @@ -0,0 +1,18 @@ +from bs4 import BeautifulSoup +from urllib import request +import os + +ttb_url = "https://web.archive.org/web/20230906095156/https://www.ttb.gov/beer/statistics" + +if not os.path.exists("ttb_stats.json"): + with open("ttb_page.html", "wb") as f: + resp = request.urlopen(ttb_url) + body = resp.read() + f.write(body) +else: + with open("ttb_page.html") as f: + body = f.read() + +# change this to lxml intead of html5lib if you can't use it +soup = BeautifulSoup(body, "html5lib") +print(soup.title) diff --git a/python/code/module-4/ex53.py b/python/code/module-4/ex53.py new file mode 100644 index 0000000..721d8bc --- /dev/null +++ b/python/code/module-4/ex53.py @@ -0,0 +1,20 @@ +import requests +from pprint import pprint +import sys +import csv + +api_url = "http://learncodethehardway.com/api/course" + +# list all courses +r = requests.get(api_url) +data = r.json() +pprint(data) + +# get one course, full=true includes all modules +r = requests.get(api_url, params={ + "course_id": 1, "full": "true" }) + +data = r.json() +pprint(data) + +# remember with? use it with csv diff --git a/python/code/module-4/ex54.py b/python/code/module-4/ex54.py new file mode 100644 index 0000000..3809a8f --- /dev/null +++ b/python/code/module-4/ex54.py @@ -0,0 +1,18 @@ +import csv +from pprint import pprint +import pandas as pd + +records = [] + +with open("ex53.csv") as csvfile: + reader = csv.DictReader(csvfile) + for row in reader: + records.append(row) + +# do you analysis here + +df = pd.DataFrame(records) + +pprint(df) + +df.to_excel("ex54.xlsx") diff --git a/python/code/module-4/ex57.py b/python/code/module-4/ex57.py new file mode 100644 index 0000000..92d1428 --- /dev/null +++ b/python/code/module-4/ex57.py @@ -0,0 +1,11 @@ +import csv +import sys + +results = [] + +with open("fixed.csv", "w") as out: + outcsv = csv.writer(out) + with open(sys.argv[1]) as f: + reader = csv.reader(f) + for row in reader: + outcsv.writerow(row[0:-1]) diff --git a/python/code/module-4/ex58.py b/python/code/module-4/ex58.py new file mode 100644 index 0000000..744ca51 --- /dev/null +++ b/python/code/module-4/ex58.py @@ -0,0 +1,21 @@ +import csv +import sys + +results = [] + +print("DROP TABLE IF EXISTS rate;") +print("CREATE TABLE IF NOT EXISTS rate (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, date DATE, currency TEXT, rate FLOAT);"); + +with open(sys.argv[1]) as f: + reader = csv.DictReader(f) + for currencies in reader: + date = currencies['Date'] + del currencies['Date'] + + for currency in currencies.keys(): + # skip the blank ones + if currency != '': + rate = currencies[currency] + rate = rate == "N/A" and "null" or rate + + print(f"INSERT INTO rate (date, currency, rate) VALUES ('{date}', '{currency}', { rate });") diff --git a/python/code/module-4/ex62.py b/python/code/module-4/ex62.py new file mode 100644 index 0000000..ee7b6fb --- /dev/null +++ b/python/code/module-4/ex62.py @@ -0,0 +1 @@ +# just here for git