From 4459769b9e5b6b5c4e2319f07f5049922c5fbb34 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Mon, 30 Jul 2018 19:45:30 -0700 Subject: [PATCH 01/52] hello, slice complete --- src/day-1-toy/fileio.py | 7 ++++--- src/day-1-toy/hello.py | 3 ++- src/day-1-toy/lists.py | 14 +++++++++----- src/day-1-toy/slice.py | 14 +++++++------- 4 files changed, 22 insertions(+), 16 deletions(-) diff --git a/src/day-1-toy/fileio.py b/src/day-1-toy/fileio.py index bc8e79b7cc..0aacf10232 100644 --- a/src/day-1-toy/fileio.py +++ b/src/day-1-toy/fileio.py @@ -1,9 +1,10 @@ # Use open to open file "foo.txt" for reading - +file = open('foo.txt', 'r') # Print all the lines in the file - +for line in file: + print(line) # Close the file - +file.close() # Use open to open file "bar.txt" for writing diff --git a/src/day-1-toy/hello.py b/src/day-1-toy/hello.py index 37968da4d4..6ee1f01872 100644 --- a/src/day-1-toy/hello.py +++ b/src/day-1-toy/hello.py @@ -1 +1,2 @@ -# Write Hello, world \ No newline at end of file +# Write Hello, world +print('Hello, world') \ No newline at end of file diff --git a/src/day-1-toy/lists.py b/src/day-1-toy/lists.py index 6076f340a9..a2157e817d 100644 --- a/src/day-1-toy/lists.py +++ b/src/day-1-toy/lists.py @@ -7,23 +7,27 @@ # For the following, DO NOT USE AN ASSIGNMENT (=). # Change x so that it is [1, 2, 3, 4] -# [command here] +x.append(4) print(x) # Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10] -# [command here] +x += y +# x.extend(y) print(x) # Change x so that it is [1, 2, 3, 4, 9, 10] -# [command here] +x.remove(8) print(x) # Change x so that it is [1, 2, 3, 4, 9, 99, 10] -# [command here] +x.insert(5, 99) +# x.insert(-1, 99) print(x) # Print the length of list x # [command here] print(len(x)) -# Using a for loop, print all the element values multiplied by 1000 \ No newline at end of file +# Using a for loop, print all the element values multiplied by 1000 +for el in x: + print(el * 1000) \ No newline at end of file diff --git a/src/day-1-toy/slice.py b/src/day-1-toy/slice.py index 3c6cb38730..c66226c286 100644 --- a/src/day-1-toy/slice.py +++ b/src/day-1-toy/slice.py @@ -1,26 +1,26 @@ a = [2, 4, 1, 7, 9, 6] # Output the second element: 4: -print() +print(a[1]) # Output the second-to-last element: 9 -print() +print(a[4]) # Output the last three elements in the array: [7, 9, 6] -print() +print(a[3: ]) # Output the two middle elements in the array: [1, 7] -print() +print(a[2 : 4]) # Output every element except the first one: [4, 1, 7, 9, 6] -print() +print(a[1:]) # Output every element except the last one: [2, 4, 1, 7, 9] -print() +print(a[:5]) # For string s... s = "Hello, world!" # Output just the 8th-12th characters: "world" -print() \ No newline at end of file +print(s[7:12]) \ No newline at end of file From 7b5d2ce6ca7966df9ff33c744aff267ae217ad21 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Mon, 30 Jul 2018 20:02:05 -0700 Subject: [PATCH 02/52] datetypes --- src/day-1-toy/bignum.py | 3 ++- src/day-1-toy/datatypes.py | 4 ++-- src/day-1-toy/fileio.py | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/day-1-toy/bignum.py b/src/day-1-toy/bignum.py index 77e8d66ffa..865465b440 100644 --- a/src/day-1-toy/bignum.py +++ b/src/day-1-toy/bignum.py @@ -1 +1,2 @@ -# Print out 2 to the 65536 power \ No newline at end of file +# Print out 2 to the 65536 power +print(pow(2, 65536)) \ No newline at end of file diff --git a/src/day-1-toy/datatypes.py b/src/day-1-toy/datatypes.py index f5967611a7..b8c6f50a05 100644 --- a/src/day-1-toy/datatypes.py +++ b/src/day-1-toy/datatypes.py @@ -2,7 +2,7 @@ y = "7" # Write a print statement that combines x + y into the integer value 12 -print(x + y) +print(x + (int(y))) # Write a print statement that combines x + y into the string value 57 -print(x + y) \ No newline at end of file +print((str(x)) + y) \ No newline at end of file diff --git a/src/day-1-toy/fileio.py b/src/day-1-toy/fileio.py index 0aacf10232..a35b1aadcd 100644 --- a/src/day-1-toy/fileio.py +++ b/src/day-1-toy/fileio.py @@ -7,7 +7,7 @@ file.close() # Use open to open file "bar.txt" for writing - +file = open('bar.txt', 'w') # Use the write() method to write three lines to the file # Close the file \ No newline at end of file From c315a4347156cab78205157ce10a9a460c686d9f Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Mon, 30 Jul 2018 20:13:32 -0700 Subject: [PATCH 03/52] modules --- src/day-1-toy/modules.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/day-1-toy/modules.py b/src/day-1-toy/modules.py index 5313fc1934..a354afebfc 100644 --- a/src/day-1-toy/modules.py +++ b/src/day-1-toy/modules.py @@ -6,13 +6,13 @@ # See docs for the sys module: https://docs.python.org/3.7/library/sys.html # Print out the command line arguments in sys.argv, one per line: +print(sys.argv) - -# Print out the plaform from sys: -print() +# Print out the platform from sys: +print(sys.platform) # Print out the Python version from sys: -print() +print(sys.version) @@ -21,11 +21,11 @@ # See the docs for the OS module: https://docs.python.org/3.7/library/os.html # Print the current process ID -print() +print(os.getpid()) # Print the current working directory (cwd): -print() +print(os.getcwd()) # Print your login name -print() +print(os.getlogin()) From c62f2698f69b449d409d2c5463151412b2ff1bc2 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Mon, 30 Jul 2018 20:44:14 -0700 Subject: [PATCH 04/52] printf, but trailing 000s --- src/day-1-toy/printf.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/day-1-toy/printf.py b/src/day-1-toy/printf.py index d4bc9abb48..374be7a25d 100644 --- a/src/day-1-toy/printf.py +++ b/src/day-1-toy/printf.py @@ -5,6 +5,10 @@ # Using the printf operator (%), print the following feeding in the values of x, # y, and z: # x is 10, y is 2.25, z is "I like turtles!" +print(f'x is {x}, y is {round(y, 2)}, z is "{z}"') +# Use the 'format' string method to print the same thing +print('x is %d, y is %f, z is "%s"' % (x, (round(y, 2)), z)) + +#trailing 000s -# Use the 'format' string method to print the same thing \ No newline at end of file From ab968681d66f42c61c4ddaca4bc83b5fad5ad1bd Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Tue, 31 Jul 2018 18:51:54 -0700 Subject: [PATCH 05/52] bignum rounding --- src/day-1-toy/printf.py | 2 +- src/day-1-toy/tuples.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/day-1-toy/printf.py b/src/day-1-toy/printf.py index 374be7a25d..8fcad08e44 100644 --- a/src/day-1-toy/printf.py +++ b/src/day-1-toy/printf.py @@ -8,7 +8,7 @@ print(f'x is {x}, y is {round(y, 2)}, z is "{z}"') # Use the 'format' string method to print the same thing -print('x is %d, y is %f, z is "%s"' % (x, (round(y, 2)), z)) +print('x is %d, y is %.2f, z is "%s"' % (x, y, z)) #trailing 000s diff --git a/src/day-1-toy/tuples.py b/src/day-1-toy/tuples.py index ec42b0cdf8..a4b782bdb5 100644 --- a/src/day-1-toy/tuples.py +++ b/src/day-1-toy/tuples.py @@ -22,7 +22,7 @@ def dist(a, b): # Write a function that prints all the values in a tuple -# def print_tuple(... +def print_tuple(t) t = (1, 2, 5, 7, 99) print_tuple(t) # Prints 1 2 5 7 99, one per line From 0770c792016e5853c32187994b7d18429e7ab9f4 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Tue, 31 Jul 2018 19:07:14 -0700 Subject: [PATCH 06/52] tuples --- src/day-1-toy/printf.py | 3 --- src/day-1-toy/tuples.py | 8 +++++--- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/day-1-toy/printf.py b/src/day-1-toy/printf.py index 8fcad08e44..4d5d75b5ee 100644 --- a/src/day-1-toy/printf.py +++ b/src/day-1-toy/printf.py @@ -9,6 +9,3 @@ # Use the 'format' string method to print the same thing print('x is %d, y is %.2f, z is "%s"' % (x, y, z)) - -#trailing 000s - diff --git a/src/day-1-toy/tuples.py b/src/day-1-toy/tuples.py index a4b782bdb5..cd15f9f0f5 100644 --- a/src/day-1-toy/tuples.py +++ b/src/day-1-toy/tuples.py @@ -22,11 +22,13 @@ def dist(a, b): # Write a function that prints all the values in a tuple -def print_tuple(t) +def print_tuple(t): + for item in t: + print(item) t = (1, 2, 5, 7, 99) print_tuple(t) # Prints 1 2 5 7 99, one per line -# Declare a tuple of 1 element then print it -u = (1) # What needs to be added to make this work? +# # Declare a tuple of 1 element then print it +u = (1,) # What needs to be added to make this work? print_tuple(u) From 0c3823a0ab70384d5420481993b5efa88d341241 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Tue, 31 Jul 2018 19:10:22 -0700 Subject: [PATCH 07/52] slice --- src/day-1-toy/slice.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/day-1-toy/slice.py b/src/day-1-toy/slice.py index c66226c286..7d835b5ed9 100644 --- a/src/day-1-toy/slice.py +++ b/src/day-1-toy/slice.py @@ -4,10 +4,10 @@ print(a[1]) # Output the second-to-last element: 9 -print(a[4]) +print(a[-2]) # Output the last three elements in the array: [7, 9, 6] -print(a[3: ]) +print(a[(len(a)-3): ]) # Output the two middle elements in the array: [1, 7] print(a[2 : 4]) @@ -16,7 +16,7 @@ print(a[1:]) # Output every element except the last one: [2, 4, 1, 7, 9] -print(a[:5]) +print(a[:(len(a)-1)]) # For string s... From 00ea91e179b133f3b4afffb891d61edd3ea0e40b Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Tue, 31 Jul 2018 19:28:57 -0700 Subject: [PATCH 08/52] started comp --- src/day-1-toy/comp.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/day-1-toy/comp.py b/src/day-1-toy/comp.py index 083e9b9140..7acf403232 100644 --- a/src/day-1-toy/comp.py +++ b/src/day-1-toy/comp.py @@ -1,13 +1,13 @@ # Write a list comprehension to produce the array [1, 2, 3, 4, 5] -y = [] +y = [i for i in range(1, 6)] print (y) # Write a list comprehension to produce the cubes of the numbers 0-9: # [0, 1, 8, 27, 64, 125, 216, 343, 512, 729] -y = [] +y = [i**3 for i in range(0, 10)] print(y) @@ -16,17 +16,17 @@ a = ["foo", "bar", "baz"] -y = [] +y = [item.upper() for item in a] print(y) -# Use a list comprehension to create a list containing only the _even_ elements -# the user entered into list x. +# # Use a list comprehension to create a list containing only the _even_ elements +# # the user entered into list x. x = input("Enter comma-separated numbers: ").split(',') -# What do you need between the square brackets to make it work? -y = [] +# # What do you need between the square brackets to make it work? +y = [i for i in x if i % 2 == 0] print(y) From cc50a0d074db4106b91211673df86ca7edc02214 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Tue, 31 Jul 2018 19:34:05 -0700 Subject: [PATCH 09/52] dicts --- src/day-1-toy/dicts.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/day-1-toy/dicts.py b/src/day-1-toy/dicts.py index eac1779a42..402bbf630c 100644 --- a/src/day-1-toy/dicts.py +++ b/src/day-1-toy/dicts.py @@ -25,5 +25,10 @@ ] # Write a loop that prints out all the field values for all the waypoints - +for i in waypoints: + print(i) # Add a new waypoint to the list +waypoints.append({"lat": 42, "lon": 42, "name": "Somewhere"}) + +for i in waypoints: + print(i) From 701c91fde0f2308f6d86698442d095d0cf7682ef Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Tue, 31 Jul 2018 19:37:36 -0700 Subject: [PATCH 10/52] some func --- src/day-1-toy/func.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/day-1-toy/func.py b/src/day-1-toy/func.py index 2b7f435ffa..7a6665b8b2 100644 --- a/src/day-1-toy/func.py +++ b/src/day-1-toy/func.py @@ -1,6 +1,12 @@ # Write a function is_even that will return true if the passed in number is even. +def is_even(n): + return n % 2 == 0 +print(is_even(5)) # Read a number from the keyboard num = input("Enter a number: ") - +if num % 2 == 0: + print('Even!') +else: + print('Odd') # Print out "Even!" if the number is even. Otherwise print "Odd" \ No newline at end of file From 2c8f8ab36c05d3df04e29fac8dfb68c3ca0363e3 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Tue, 31 Jul 2018 20:01:22 -0700 Subject: [PATCH 11/52] args --- src/day-1-toy/args.py | 58 ++++++++++++++++++++++++------------------- src/day-1-toy/comp.py | 2 +- src/day-1-toy/func.py | 2 +- 3 files changed, 35 insertions(+), 27 deletions(-) diff --git a/src/day-1-toy/args.py b/src/day-1-toy/args.py index 06a830e4c8..1344a011bf 100644 --- a/src/day-1-toy/args.py +++ b/src/day-1-toy/args.py @@ -4,14 +4,16 @@ # Write a function f1 that takes two integer positional arguments and returns # the sum. This is what you'd consider to be a regular, normal function. -#def f1(... +def f1(a, b): + return a + b print(f1(1, 2)) # Write a function f2 that takes any number of iteger arguments and prints the # sum. Google for "python arbitrary arguments" and look for "*args" -# def f2(... +def f2(*args): + return sum(args) print(f2(1)) # Should print 1 print(f2(1, 3)) # Should print 4 @@ -20,38 +22,44 @@ a = [7, 6, 5, 4] -# What thing do you have to add to make this work? -print(f2(a)) # Should print 22 +# # What thing do you have to add to make this work? +print(f2(*a)) # Should print 22 -# Write a function f3 that accepts either one or two arguments. If one argument, -# it returns that value plus 1. If two arguments, it returns the sum of the -# arguments. Google "python default arguments" for a hint. +# # Write a function f3 that accepts either one or two arguments. If one argument, +# # it returns that value plus 1. If two arguments, it returns the sum of the +# # arguments. Google "python default arguments" for a hint. -#def f3(... +def f3(arg, arg2=None): + if arg2 is None: + return arg + 1 + else: + return arg + arg2 print(f3(1, 2)) # Should print 3 print(f3(8)) # Should print 9 -# Write a function f4 that accepts an arbitrary number of keyword arguments and -# prints ouf the keys and values like so: -# -# key: foo, value: bar -# key: baz, value: 12 -# -# Google "python keyword arguments". +# # Write a function f4 that accepts an arbitrary number of keyword arguments and +# # prints ouf the keys and values like so: +# # +# # key: foo, value: bar +# # key: baz, value: 12 +# # +# # Google "python keyword arguments". -#def f4(... +def f4(*args, **kwargs): + for key, value in kwargs.items(): + print(f'key: {key}, value: {value}') -# Should print -# key: a, value: 12 -# key: b, value: 30 +# # Should print +# # key: a, value: 12 +# # key: b, value: 30 f4(a=12, b=30) -# Should print -# key: city, value: Berkeley -# key: population, value: 121240 -# key: founded, value: "March 23, 1868" +# # Should print +# # key: city, value: Berkeley +# # key: population, value: 121240 +# # key: founded, value: "March 23, 1868" f4(city="Berkeley", population=121240, founded="March 23, 1868") d = { @@ -59,5 +67,5 @@ "hp": 3 } -# What thing do you have to add to make this work? -f4(d) \ No newline at end of file +# # What thing do you have to add to make this work? +f4(**d) \ No newline at end of file diff --git a/src/day-1-toy/comp.py b/src/day-1-toy/comp.py index 7acf403232..edb9f086b4 100644 --- a/src/day-1-toy/comp.py +++ b/src/day-1-toy/comp.py @@ -26,7 +26,7 @@ x = input("Enter comma-separated numbers: ").split(',') # # What do you need between the square brackets to make it work? -y = [i for i in x if i % 2 == 0] +y = [i for i in x if int(i) % 2 == 0] print(y) diff --git a/src/day-1-toy/func.py b/src/day-1-toy/func.py index 7a6665b8b2..b3cecf03ea 100644 --- a/src/day-1-toy/func.py +++ b/src/day-1-toy/func.py @@ -5,7 +5,7 @@ def is_even(n): print(is_even(5)) # Read a number from the keyboard num = input("Enter a number: ") -if num % 2 == 0: +if int(num) % 2 == 0: print('Even!') else: print('Odd') From 6592b5819afa401c39af0b29d13bd44acf501296 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Tue, 31 Jul 2018 20:51:34 -0700 Subject: [PATCH 12/52] scope --- src/day-1-toy/scope.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/day-1-toy/scope.py b/src/day-1-toy/scope.py index 68ecc6c412..7d1efb608e 100644 --- a/src/day-1-toy/scope.py +++ b/src/day-1-toy/scope.py @@ -5,6 +5,7 @@ x = 12 def changeX(): + global x x = 99 changeX() @@ -19,6 +20,7 @@ def outer(): y = 120 def inner(): + nonlocal y y = 999 inner() @@ -26,5 +28,4 @@ def inner(): # This prints 120. What do we have to change in inner() to get it to print # 999? Google "python nested function scope". print(y) - outer() \ No newline at end of file From d333ac4562a1838c8f79ea6cb3257bf2b8c6f839 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Wed, 1 Aug 2018 10:44:19 -0700 Subject: [PATCH 13/52] fileio --- src/day-1-toy/bar.txt | 1 + src/day-1-toy/fileio.py | 7 +++++-- 2 files changed, 6 insertions(+), 2 deletions(-) create mode 100644 src/day-1-toy/bar.txt diff --git a/src/day-1-toy/bar.txt b/src/day-1-toy/bar.txt new file mode 100644 index 0000000000..01a25e0ac6 --- /dev/null +++ b/src/day-1-toy/bar.txt @@ -0,0 +1 @@ +Quarrel, sir? No, sir. \ No newline at end of file diff --git a/src/day-1-toy/fileio.py b/src/day-1-toy/fileio.py index a35b1aadcd..1c096caa6d 100644 --- a/src/day-1-toy/fileio.py +++ b/src/day-1-toy/fileio.py @@ -9,5 +9,8 @@ # Use open to open file "bar.txt" for writing file = open('bar.txt', 'w') # Use the write() method to write three lines to the file - -# Close the file \ No newline at end of file +file.write(line) +file.write(line) +file.write(line) +# Close the file +file.close() \ No newline at end of file From 07144a23e7e22a52defd50679773c8991c8fe633 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Wed, 1 Aug 2018 10:53:47 -0700 Subject: [PATCH 14/52] obj --- src/day-1-toy/obj.py | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/src/day-1-toy/obj.py b/src/day-1-toy/obj.py index 84c78a2f53..9b35ce4281 100644 --- a/src/day-1-toy/obj.py +++ b/src/day-1-toy/obj.py @@ -1,21 +1,38 @@ # Make a class LatLon that can be passed parameters `lat` and `lon` to the # constructor - +class LatLon: + def __init__(self, lat, lon): + self.lat = lat + self.lon = lon # Make a class Waypoint that can be passed parameters `name`, `lat`, and `lon` to the # constructor. It should inherit from LatLon. +class Waypoint(LatLon): + def __init__(self, name, lat, lon): + LatLon.__init__(self, lat, lon) + self.name = name + def __repr__(self): + return f"Waypoint: {self.name}, {self.lat}, {self.lon}" + # Make a class Geocache that can be passed parameters `name`, `difficulty`, # `size`, `lat`, and `lon` to the constructor. What should it inherit from? - +class Geocache(Waypoint): + def __init__(self, name, difficulty, size, lat, lon): + Waypoint.__init__(self, name, lat, lon) + self.difficulty = difficulty + self.size = size + def __repr__(self): + return f"Geocache: {self.name}, {self.difficulty}, {self.size}, {self.lat}, {self.lon}" # Make a new waypoint "Catacombs", 41.70505, -121.51521 +w = Waypoint("Catacombs", 41.70505, -121.51521) # Print it -# +print(w) # Without changing the following line, how can you make it print into something # more human-readable? -print(w) +# print(w) # Make a new geocache "Newberry Views", diff 1.5, size 2, 44.052137, -121.41556 - +g = Geocache("Newberry Views", 1.5, 2, 44.052137, -121.41556) # Print it--also make this print more nicely print(g) From e058db2807485bec203be51d3bba7d2a2b3469da Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Wed, 1 Aug 2018 11:40:01 -0700 Subject: [PATCH 15/52] cal wip --- src/day-1-toy/cal.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/day-1-toy/cal.py b/src/day-1-toy/cal.py index 2a3771eb5b..76ef125418 100644 --- a/src/day-1-toy/cal.py +++ b/src/day-1-toy/cal.py @@ -14,3 +14,12 @@ # docs for the calendar module closely. import sys +import calendar +import datetime + +month_year = input ("Enter a month and year: ") +# print(month_year) +# # itermonthdates(month_year[0], month_year[1]) +# str = calendar.monthcalendar(1999, 1) +# print(str) +print(sys.argv) From c8cbe3eb78a7b219ac806437401200a5f14cd8b0 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Wed, 1 Aug 2018 20:15:21 -0700 Subject: [PATCH 16/52] adv printing room and description --- src/day-1-toy/cal.py | 12 ++++++------ src/days-2-4-adv/adv.py | 28 ++++++++++++++++++++++++---- src/days-2-4-adv/player.py | 3 +++ src/days-2-4-adv/room.py | 8 +++++++- 4 files changed, 40 insertions(+), 11 deletions(-) diff --git a/src/day-1-toy/cal.py b/src/day-1-toy/cal.py index 76ef125418..5e29a0837d 100644 --- a/src/day-1-toy/cal.py +++ b/src/day-1-toy/cal.py @@ -17,9 +17,9 @@ import calendar import datetime -month_year = input ("Enter a month and year: ") -# print(month_year) -# # itermonthdates(month_year[0], month_year[1]) -# str = calendar.monthcalendar(1999, 1) -# print(str) -print(sys.argv) +month = int(input("Enter a month 1 - 12: ")) +year = int(input("Enter a 4 digit year: ")) +# str = calendar.itermonthdates(year, month) +str = calendar.monthcalendar(year, month) +print(str) +# print(sys.argv) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index c9e26b0f85..d06df22fb4 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -1,4 +1,5 @@ from room import Room +from player import Player # Declare all the rooms @@ -19,6 +20,8 @@ 'treasure': Room("Treasure Chamber", """You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by earlier adventurers. The only exit is to the south."""), + +'library': Room("Library", """Yes, we do have copies of Harry Potter."""), } @@ -32,19 +35,36 @@ room['narrow'].w_to = room['foyer'] room['narrow'].n_to = room['treasure'] room['treasure'].s_to = room['narrow'] +room['overlook'].w_to = room['library'] +room['library'].e_to = room['overlook'] # # Main # # Make a new player object that is currently in the 'outside' room. - +lola = Player( room['outside']) # Write a loop that: -# +while not dir == "q": # * Prints the current room name + print(lola.room) # * Prints the current description (the textwrap module might be useful here). -# * Waits for user input and decides what to do. -# + print(lola.room.description) +# * Waits for user input + dir = input("Please enter a direction... n, s, e, w OR q to quit the game: ") +#decides what to do. + if dir == "n": + print('North') + + # elif south + # elif east + # elif west + # elif invalid + + # else: + # dir == "q": + # print("Quitter!") + # return "Exit" # If the user enters a cardinal direction, attempt to move to the room there. # Print an error message if the movement isn't allowed. # diff --git a/src/days-2-4-adv/player.py b/src/days-2-4-adv/player.py index d79a175029..96e9e533bb 100644 --- a/src/days-2-4-adv/player.py +++ b/src/days-2-4-adv/player.py @@ -1,2 +1,5 @@ # Write a class to hold player information, e.g. what room they are in # currently. +class Player: + def __init__(self, room): + self.room = room \ No newline at end of file diff --git a/src/days-2-4-adv/room.py b/src/days-2-4-adv/room.py index 24c07ad4c8..0bd90a8784 100644 --- a/src/days-2-4-adv/room.py +++ b/src/days-2-4-adv/room.py @@ -1,2 +1,8 @@ # Implement a class to hold room information. This should have name and -# description attributes. \ No newline at end of file +# description attributes. +class Room: + def __init__(self, name, description): + self.name = name + self.description = description + def __repr__(self): + return f"{self.name}" \ No newline at end of file From afaab8d709f96c5c2bff828dc5a6951fd29673c2 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Wed, 1 Aug 2018 20:42:57 -0700 Subject: [PATCH 17/52] move between rooms, no error --- src/days-2-4-adv/adv.py | 28 +++++++++++++++------------- src/days-2-4-adv/player.py | 3 ++- 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index d06df22fb4..b2f543511b 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -43,28 +43,30 @@ # # Make a new player object that is currently in the 'outside' room. -lola = Player( room['outside']) +player = Player( 'Lola', room['outside']) # Write a loop that: while not dir == "q": # * Prints the current room name - print(lola.room) + print(player.room, ":", player.room.description) # * Prints the current description (the textwrap module might be useful here). - print(lola.room.description) + # * Waits for user input dir = input("Please enter a direction... n, s, e, w OR q to quit the game: ") #decides what to do. if dir == "n": - print('North') - - # elif south - # elif east - # elif west + player.room = getattr(player.room, dir + '_to') + elif dir == "s": + player.room = getattr(player.room, dir + '_to') + elif dir == "e": + player.room = getattr(player.room, dir + '_to') + elif dir == "w": + player.room = getattr(player.room, dir + '_to') # elif invalid - - # else: - # dir == "q": - # print("Quitter!") - # return "Exit" + elif dir == "q": + print("Quitter!") + "Exit" + else: + print("Chose a direction or q to quit") # If the user enters a cardinal direction, attempt to move to the room there. # Print an error message if the movement isn't allowed. # diff --git a/src/days-2-4-adv/player.py b/src/days-2-4-adv/player.py index 96e9e533bb..c056a7ac23 100644 --- a/src/days-2-4-adv/player.py +++ b/src/days-2-4-adv/player.py @@ -1,5 +1,6 @@ # Write a class to hold player information, e.g. what room they are in # currently. class Player: - def __init__(self, room): + def __init__(self, name, room): + self.name = name self.room = room \ No newline at end of file From b93226b4b0d21f458e106a57618698cd064bb3dd Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Thu, 2 Aug 2018 19:38:42 -0700 Subject: [PATCH 18/52] lots of attempts, still not printing error --- src/days-2-4-adv/adv.py | 49 +++++++++++++++++++++++------------------ 1 file changed, 28 insertions(+), 21 deletions(-) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index b2f543511b..8972f60018 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -4,24 +4,24 @@ # Declare all the rooms room = { - 'outside': Room("Outside Cave Entrance", + 'outside': Room("--Outside Cave Entrance--", "North of you, the cave mount beckons"), - 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty + 'foyer': Room("--Foyer--", """Dim light filters in from the south. Dusty passages run north and east."""), - 'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling + 'overlook': Room("--Grand Overlook--", """A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in the distance, but there is no way across the chasm."""), - 'narrow': Room("Narrow Passage", """The narrow passage bends here from west + 'narrow': Room("--Narrow Passage--", """The narrow passage bends here from west to north. The smell of gold permeates the air."""), - 'treasure': Room("Treasure Chamber", """You've found the long-lost treasure + 'treasure': Room("$$--Treasure Chamber--$$", """You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by earlier adventurers. The only exit is to the south."""), -'library': Room("Library", """Yes, we do have copies of Harry Potter."""), +'library': Room("--Library--", """Shhhhhhh."""), } @@ -44,29 +44,36 @@ # Make a new player object that is currently in the 'outside' room. player = Player( 'Lola', room['outside']) + +print(f"Welcome {player.name}") # Write a loop that: while not dir == "q": # * Prints the current room name - print(player.room, ":", player.room.description) + print(player.room, "\n", player.room.description) # * Prints the current description (the textwrap module might be useful here). # * Waits for user input dir = input("Please enter a direction... n, s, e, w OR q to quit the game: ") -#decides what to do. - if dir == "n": - player.room = getattr(player.room, dir + '_to') - elif dir == "s": - player.room = getattr(player.room, dir + '_to') - elif dir == "e": - player.room = getattr(player.room, dir + '_to') - elif dir == "w": - player.room = getattr(player.room, dir + '_to') - # elif invalid - elif dir == "q": - print("Quitter!") - "Exit" + + if dir is "n" or dir is "e" or dir is "w" or dir is "s": + if hasattr(player.room, dir + '_to'): + player.room = getattr(player.room, dir + '_to') + else: + print("Wall") else: - print("Chose a direction or q to quit") + print("**Choose a direction or q to quit**") +# elif dir == "n" or "s" or "e" or "w": +# if hasattr(player.room, dir+'_to'): +# if getattr(player.room, dir + '_to') == player.room: +# print('Ther') +# else: +# player.room = getattr(player.room, dir + '_to') +# # else: +# # print("There's no door in that direction") + + +print("Quitter!") +"Exit" # If the user enters a cardinal direction, attempt to move to the room there. # Print an error message if the movement isn't allowed. # From 4ab1d3943c9462a1955d8f59db5f223666f79c85 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Thu, 2 Aug 2018 19:42:24 -0700 Subject: [PATCH 19/52] errors working --- src/days-2-4-adv/adv.py | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index 8972f60018..cec73f3326 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -6,21 +6,16 @@ room = { 'outside': Room("--Outside Cave Entrance--", "North of you, the cave mount beckons"), - 'foyer': Room("--Foyer--", """Dim light filters in from the south. Dusty passages run north and east."""), - 'overlook': Room("--Grand Overlook--", """A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in the distance, but there is no way across the chasm."""), - 'narrow': Room("--Narrow Passage--", """The narrow passage bends here from west to north. The smell of gold permeates the air."""), - 'treasure': Room("$$--Treasure Chamber--$$", """You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by earlier adventurers. The only exit is to the south."""), - 'library': Room("--Library--", """Shhhhhhh."""), } @@ -46,10 +41,11 @@ player = Player( 'Lola', room['outside']) print(f"Welcome {player.name}") +print(player.room, "\n", player.room.description) # Write a loop that: while not dir == "q": # * Prints the current room name - print(player.room, "\n", player.room.description) + # * Prints the current description (the textwrap module might be useful here). # * Waits for user input @@ -57,10 +53,11 @@ if dir is "n" or dir is "e" or dir is "w" or dir is "s": if hasattr(player.room, dir + '_to'): - player.room = getattr(player.room, dir + '_to') + player.room = getattr(player.room, dir + '_to') + print(player.room, "\n", player.room.description) else: - print("Wall") - else: + print("That direction is a dead end.") + elif dir != "q": print("**Choose a direction or q to quit**") # elif dir == "n" or "s" or "e" or "w": # if hasattr(player.room, dir+'_to'): From 9b8605fdf29d702b89614c31a7ad7190fe97fa33 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Thu, 2 Aug 2018 19:45:02 -0700 Subject: [PATCH 20/52] clean up code --- src/days-2-4-adv/adv.py | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index cec73f3326..09a25a2852 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -40,7 +40,7 @@ # Make a new player object that is currently in the 'outside' room. player = Player( 'Lola', room['outside']) -print(f"Welcome {player.name}") +print(f"Welcome, {player.name}! Let's begin our adventure:") print(player.room, "\n", player.room.description) # Write a loop that: while not dir == "q": @@ -56,18 +56,9 @@ player.room = getattr(player.room, dir + '_to') print(player.room, "\n", player.room.description) else: - print("That direction is a dead end.") + print("xx--That direction is a dead end.--x") elif dir != "q": print("**Choose a direction or q to quit**") -# elif dir == "n" or "s" or "e" or "w": -# if hasattr(player.room, dir+'_to'): -# if getattr(player.room, dir + '_to') == player.room: -# print('Ther') -# else: -# player.room = getattr(player.room, dir + '_to') -# # else: -# # print("There's no door in that direction") - print("Quitter!") "Exit" From 8e150759dc537750f637c9e16e177cd183897af9 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Fri, 3 Aug 2018 11:19:42 -0700 Subject: [PATCH 21/52] updated cal.py formatting --- src/day-1-toy/cal.py | 19 ++++++++++++++----- src/day-1-toy/func.py | 2 +- src/day-1-toy/obj.py | 4 ++-- src/days-2-4-adv/adv.py | 7 +++---- 4 files changed, 20 insertions(+), 12 deletions(-) diff --git a/src/day-1-toy/cal.py b/src/day-1-toy/cal.py index 5e29a0837d..5fed4ad0d5 100644 --- a/src/day-1-toy/cal.py +++ b/src/day-1-toy/cal.py @@ -17,9 +17,18 @@ import calendar import datetime -month = int(input("Enter a month 1 - 12: ")) -year = int(input("Enter a 4 digit year: ")) -# str = calendar.itermonthdates(year, month) -str = calendar.monthcalendar(year, month) +# month = int(input("Enter a month 1 - 12: ")) +# year = int(input("Enter a 4 digit year: ")) + +month = sys.argv[1] +year = sys.argv[2] + +# if month == None: +# month = 8 +# if year == None: +# year = 2018 + +c = calendar.TextCalendar(calendar.SUNDAY) +str = c.formatmonth(int(year), int(month)) print(str) -# print(sys.argv) + diff --git a/src/day-1-toy/func.py b/src/day-1-toy/func.py index b3cecf03ea..6b8e12bf81 100644 --- a/src/day-1-toy/func.py +++ b/src/day-1-toy/func.py @@ -2,7 +2,7 @@ def is_even(n): return n % 2 == 0 -print(is_even(5)) +# print(is_even(5)) # Read a number from the keyboard num = input("Enter a number: ") if int(num) % 2 == 0: diff --git a/src/day-1-toy/obj.py b/src/day-1-toy/obj.py index 9b35ce4281..44f8bce352 100644 --- a/src/day-1-toy/obj.py +++ b/src/day-1-toy/obj.py @@ -10,7 +10,7 @@ class Waypoint(LatLon): def __init__(self, name, lat, lon): LatLon.__init__(self, lat, lon) self.name = name - def __repr__(self): + def __str__(self): return f"Waypoint: {self.name}, {self.lat}, {self.lon}" @@ -18,7 +18,7 @@ def __repr__(self): # `size`, `lat`, and `lon` to the constructor. What should it inherit from? class Geocache(Waypoint): def __init__(self, name, difficulty, size, lat, lon): - Waypoint.__init__(self, name, lat, lon) + super().__init__(name, lat, lon) self.difficulty = difficulty self.size = size def __repr__(self): diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index 09a25a2852..5bf96892f5 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -45,10 +45,9 @@ # Write a loop that: while not dir == "q": # * Prints the current room name - # * Prints the current description (the textwrap module might be useful here). +# * Waits for user input * -# * Waits for user input dir = input("Please enter a direction... n, s, e, w OR q to quit the game: ") if dir is "n" or dir is "e" or dir is "w" or dir is "s": @@ -56,11 +55,11 @@ player.room = getattr(player.room, dir + '_to') print(player.room, "\n", player.room.description) else: - print("xx--That direction is a dead end.--x") + print("xx--That direction is a dead end.--xx") elif dir != "q": print("**Choose a direction or q to quit**") -print("Quitter!") +print("You quit the adventure! :( ") "Exit" # If the user enters a cardinal direction, attempt to move to the room there. # Print an error message if the movement isn't allowed. From 8afd74309061b74c5401f1326476c1127394abbb Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Mon, 6 Aug 2018 20:54:51 -0700 Subject: [PATCH 22/52] items and actions, inventory, menu --- src/days-2-4-adv/adv.py | 76 +++++++++++++++++++++++++++++--------- src/days-2-4-adv/item.py | 6 +++ src/days-2-4-adv/player.py | 5 ++- src/days-2-4-adv/room.py | 14 ++++++- 4 files changed, 80 insertions(+), 21 deletions(-) create mode 100644 src/days-2-4-adv/item.py diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index 5bf96892f5..83fadc5fe4 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -1,25 +1,25 @@ from room import Room from player import Player +from item import Item # Declare all the rooms room = { 'outside': Room("--Outside Cave Entrance--", - "North of you, the cave mount beckons"), + "North of you, the cave mount beckons", [Item('Key', "This key opens something")]), 'foyer': Room("--Foyer--", """Dim light filters in from the south. Dusty -passages run north and east."""), +passages run north and east.""", [Item('Lantern', 'Use this lantern to light the way ahead')]), 'overlook': Room("--Grand Overlook--", """A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in -the distance, but there is no way across the chasm."""), +the distance, but there is no way across the chasm.""", [Item('Sword', 'It is dangerous to go alone. Take this sword')]), 'narrow': Room("--Narrow Passage--", """The narrow passage bends here from west -to north. The smell of gold permeates the air."""), +to north. The smell of gold permeates the air.""", [Item('Coins', 'These coins look like they are worth a lot of money')]), 'treasure': Room("$$--Treasure Chamber--$$", """You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by -earlier adventurers. The only exit is to the south."""), -'library': Room("--Library--", """Shhhhhhh."""), +earlier adventurers. The only exit is to the south.""", [Item('Potion', 'An unknown potion. Use at your own risk')]), +'library': Room("--Library--", """Shhhhhhh.""", [Item('Book', 'Relax and look at this book')]), } - # Link rooms together room['outside'].n_to = room['foyer'] @@ -38,7 +38,7 @@ # # Make a new player object that is currently in the 'outside' room. -player = Player( 'Lola', room['outside']) +player = Player( 'Lola', room['outside'], [ ]) print(f"Welcome, {player.name}! Let's begin our adventure:") print(player.room, "\n", player.room.description) @@ -48,20 +48,62 @@ # * Prints the current description (the textwrap module might be useful here). # * Waits for user input * - dir = input("Please enter a direction... n, s, e, w OR q to quit the game: ") + dir = input("------------------\nPlease enter a direction... n, s, e, w OR q to quit the game. Press m for more options. \n---------\n") + parsed_dir = dir.split() + + if len(parsed_dir) is 1: + # directional inputs + if dir is "n" or dir is "e" or dir is "w" or dir is "s": + if hasattr(player.room, dir + '_to'): + player.room = getattr(player.room, dir + '_to') + print(player.room, "\n", player.room.description, "\n") + print("Items in this room:") + if len(player.room.items) == 0: + print("none") + else: + for i in player.room.items: + print("\t" + i.name + ": " + i.description) + else: + print("xx--That direction is a dead end.--xx") + elif dir == "i" or dir == "inventory": + print("Inventory:") + for item in player.inventory: + print("\t" + item.name) + elif dir == "m" or dir == "menu": + print("Move North | n \nMove South | s \nMove East | e \nMove West | w \nItems | get item or drop item \nInventory | i ") + elif dir != "q": + print("**Invalid choice. m for options **") - if dir is "n" or dir is "e" or dir is "w" or dir is "s": - if hasattr(player.room, dir + '_to'): - player.room = getattr(player.room, dir + '_to') - print(player.room, "\n", player.room.description) - else: - print("xx--That direction is a dead end.--xx") - elif dir != "q": - print("**Choose a direction or q to quit**") + + if len(parsed_dir) > 1: + action = parsed_dir[0] + item = "" + for i in range(1, len(parsed_dir)): + item += parsed_dir[i] + ' ' + item = item.strip() + if action == "g" or action == "get": + for i in player.room.items: + if parsed_dir[1] == i.name: + print("Adding item to inventory") + # put item in player inventory + player.inventory.append(i) + # remove item from room inventory + player.room.items.remove(i) + elif action == "d" or action == "drop": + for i in player.room.items: + if parsed_dir[1] == i.name: + print("Removing item to inventory") + # put item in player inventory + player.inventory.pop(i) + # remove item from room inventory + player.room.items.append(i) print("You quit the adventure! :( ") "Exit" # If the user enters a cardinal direction, attempt to move to the room there. # Print an error message if the movement isn't allowed. # # If the user enters "q", quit the game. + + + diff --git a/src/days-2-4-adv/item.py b/src/days-2-4-adv/item.py new file mode 100644 index 0000000000..b1456eac8c --- /dev/null +++ b/src/days-2-4-adv/item.py @@ -0,0 +1,6 @@ +class Item: + def __init__(self, name, description): + self.name = name + self.description = description + def __repr__(self): + return f"{self.name} : {self.description}" \ No newline at end of file diff --git a/src/days-2-4-adv/player.py b/src/days-2-4-adv/player.py index c056a7ac23..3c10668eb4 100644 --- a/src/days-2-4-adv/player.py +++ b/src/days-2-4-adv/player.py @@ -1,6 +1,7 @@ # Write a class to hold player information, e.g. what room they are in # currently. class Player: - def __init__(self, name, room): + def __init__(self, name, room, inventory): self.name = name - self.room = room \ No newline at end of file + self.room = room + self.inventory = inventory diff --git a/src/days-2-4-adv/room.py b/src/days-2-4-adv/room.py index 0bd90a8784..8b85772628 100644 --- a/src/days-2-4-adv/room.py +++ b/src/days-2-4-adv/room.py @@ -1,8 +1,18 @@ # Implement a class to hold room information. This should have name and # description attributes. class Room: - def __init__(self, name, description): + def __init__(self, name, description, items): self.name = name self.description = description + self.items = items + def __repr__(self): - return f"{self.name}" \ No newline at end of file + return f"{self.name}" + + # def view_items(self): + # print("Items found in this room") + # if len(self.items) == 0: + # print("none") + # else: + # for i in self.items: + # print("\t" + i) \ No newline at end of file From 785ab3533f67a81a4200fd1fbf31d95b3a86fc4e Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Tue, 7 Aug 2018 19:13:51 -0700 Subject: [PATCH 23/52] added new player name functionality --- src/days-2-4-adv/adv.py | 10 ++++------ src/days-2-4-adv/room.py | 4 ++-- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index 83fadc5fe4..ca73a21aa4 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -38,12 +38,13 @@ # # Make a new player object that is currently in the 'outside' room. -player = Player( 'Lola', room['outside'], [ ]) +name = input('Hello, player. What is your name?') +player = Player( name, room['outside'], [ ]) print(f"Welcome, {player.name}! Let's begin our adventure:") print(player.room, "\n", player.room.description) # Write a loop that: -while not dir == "q": +while not dir is "q" or dir is "quit": # * Prints the current room name # * Prints the current description (the textwrap module might be useful here). # * Waits for user input * @@ -70,7 +71,7 @@ for item in player.inventory: print("\t" + item.name) elif dir == "m" or dir == "menu": - print("Move North | n \nMove South | s \nMove East | e \nMove West | w \nItems | get item or drop item \nInventory | i ") + print("Move North | n \nMove South | s \nMove East | e \nMove West | w \nItems | get item or drop item \nInventory | i\nQuit | q") elif dir != "q": print("**Invalid choice. m for options **") @@ -104,6 +105,3 @@ # Print an error message if the movement isn't allowed. # # If the user enters "q", quit the game. - - - diff --git a/src/days-2-4-adv/room.py b/src/days-2-4-adv/room.py index 8b85772628..60f59a904c 100644 --- a/src/days-2-4-adv/room.py +++ b/src/days-2-4-adv/room.py @@ -12,7 +12,7 @@ def __repr__(self): # def view_items(self): # print("Items found in this room") # if len(self.items) == 0: - # print("none") + # print("none") # else: # for i in self.items: - # print("\t" + i) \ No newline at end of file + # print("\t" + i) From a41c09ff8f8523040f5af4f0c7f076ee7496320e Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Tue, 7 Aug 2018 19:33:47 -0700 Subject: [PATCH 24/52] input to lower case --- src/days-2-4-adv/adv.py | 32 ++++++++++++++------------------ 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index ca73a21aa4..d17a81c99b 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -5,19 +5,14 @@ # Declare all the rooms room = { - 'outside': Room("--Outside Cave Entrance--", - "North of you, the cave mount beckons", [Item('Key', "This key opens something")]), - 'foyer': Room("--Foyer--", """Dim light filters in from the south. Dusty -passages run north and east.""", [Item('Lantern', 'Use this lantern to light the way ahead')]), - 'overlook': Room("--Grand Overlook--", """A steep cliff appears before you, falling -into the darkness. Ahead to the north, a light flickers in + 'outside': Room("--Outside Cave Entrance--", "North of you, the cave mount beckons", [Item('Key', "This key opens something")]), + 'foyer': Room("--Foyer--", """Dim light filters in from the south. Dusty passages run north and east.""", [Item('Lantern', 'Use this lantern to light the way ahead')]), + 'overlook': Room("--Grand Overlook--", """A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in the distance, but there is no way across the chasm.""", [Item('Sword', 'It is dangerous to go alone. Take this sword')]), - 'narrow': Room("--Narrow Passage--", """The narrow passage bends here from west -to north. The smell of gold permeates the air.""", [Item('Coins', 'These coins look like they are worth a lot of money')]), - 'treasure': Room("$$--Treasure Chamber--$$", """You've found the long-lost treasure -chamber! Sadly, it has already been completely emptied by + 'narrow': Room("--Narrow Passage--", """The narrow passage bends here from west to north. The smell of gold permeates the air.""", [Item('Coins', 'These coins look like they are worth a lot of money')]), + 'treasure': Room("$$--Treasure Chamber--$$", """You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by earlier adventurers. The only exit is to the south.""", [Item('Potion', 'An unknown potion. Use at your own risk')]), -'library': Room("--Library--", """Shhhhhhh.""", [Item('Book', 'Relax and look at this book')]), + 'library': Room("--Library--", """Shhhhhhh.""", [Item('Book', 'Relax and look at this book')]), } # Link rooms together @@ -38,23 +33,23 @@ # # Make a new player object that is currently in the 'outside' room. -name = input('Hello, player. What is your name?') +name = input('Hello, player. What is your name? ') player = Player( name, room['outside'], [ ]) print(f"Welcome, {player.name}! Let's begin our adventure:") print(player.room, "\n", player.room.description) # Write a loop that: -while not dir is "q" or dir is "quit": +while dir != "q" and dir != "quit": # * Prints the current room name # * Prints the current description (the textwrap module might be useful here). # * Waits for user input * - dir = input("------------------\nPlease enter a direction... n, s, e, w OR q to quit the game. Press m for more options. \n---------\n") - parsed_dir = dir.split() + dir = input("------------------\nPlease enter a direction... n, s, e, w OR q to quit the game. Press m for more options. \n---------\n").lower() + parsed_dir = dir.lower().split() if len(parsed_dir) is 1: # directional inputs - if dir is "n" or dir is "e" or dir is "w" or dir is "s": + if dir == "n" or dir == "e" or dir == "w" or dir == "s": if hasattr(player.room, dir + '_to'): player.room = getattr(player.room, dir + '_to') print(player.room, "\n", player.room.description, "\n") @@ -85,7 +80,8 @@ if action == "g" or action == "get": for i in player.room.items: - if parsed_dir[1] == i.name: + if parsed_dir[1] == i.name.lower(): + print(i.name) print("Adding item to inventory") # put item in player inventory player.inventory.append(i) @@ -93,7 +89,7 @@ player.room.items.remove(i) elif action == "d" or action == "drop": for i in player.room.items: - if parsed_dir[1] == i.name: + if parsed_dir[1] == i.name.lower(): print("Removing item to inventory") # put item in player inventory player.inventory.pop(i) From 20a02a18da68db5cbede179c9833d114de49346e Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Tue, 7 Aug 2018 19:59:56 -0700 Subject: [PATCH 25/52] drop method working --- src/days-2-4-adv/adv.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index d17a81c99b..d14fabcf1f 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -36,7 +36,7 @@ name = input('Hello, player. What is your name? ') player = Player( name, room['outside'], [ ]) -print(f"Welcome, {player.name}! Let's begin our adventure:") +print(f"\n***Welcome, {player.name}! Let's begin our adventure: ***\n") print(player.room, "\n", player.room.description) # Write a loop that: while dir != "q" and dir != "quit": @@ -66,7 +66,7 @@ for item in player.inventory: print("\t" + item.name) elif dir == "m" or dir == "menu": - print("Move North | n \nMove South | s \nMove East | e \nMove West | w \nItems | get item or drop item \nInventory | i\nQuit | q") + print("Move North | n \nMove South | s \nMove East | e \nMove West | w \nPick Up Item | get (item name) \n Drop Item | drop (item name) \nInventory | i\nQuit | q") elif dir != "q": print("**Invalid choice. m for options **") @@ -81,18 +81,17 @@ if action == "g" or action == "get": for i in player.room.items: if parsed_dir[1] == i.name.lower(): - print(i.name) print("Adding item to inventory") # put item in player inventory player.inventory.append(i) # remove item from room inventory player.room.items.remove(i) elif action == "d" or action == "drop": - for i in player.room.items: + for i in player.inventory: if parsed_dir[1] == i.name.lower(): - print("Removing item to inventory") + print("Removing item from inventory") # put item in player inventory - player.inventory.pop(i) + player.inventory.remove(i) # remove item from room inventory player.room.items.append(i) print("You quit the adventure! :( ") From 093068d5bf7591a730521651c98feb5600dd277b Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Tue, 7 Aug 2018 21:06:38 -0700 Subject: [PATCH 26/52] changing theme to Doctor Who --- src/days-2-4-adv/adv.py | 46 ++++++++++++++++++++++++----------------- 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index d14fabcf1f..259ca2f8be 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -5,28 +5,36 @@ # Declare all the rooms room = { - 'outside': Room("--Outside Cave Entrance--", "North of you, the cave mount beckons", [Item('Key', "This key opens something")]), - 'foyer': Room("--Foyer--", """Dim light filters in from the south. Dusty passages run north and east.""", [Item('Lantern', 'Use this lantern to light the way ahead')]), - 'overlook': Room("--Grand Overlook--", """A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in -the distance, but there is no way across the chasm.""", [Item('Sword', 'It is dangerous to go alone. Take this sword')]), - 'narrow': Room("--Narrow Passage--", """The narrow passage bends here from west to north. The smell of gold permeates the air.""", [Item('Coins', 'These coins look like they are worth a lot of money')]), - 'treasure': Room("$$--Treasure Chamber--$$", """You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by + 'outside': Room("--Outside--", "There is a blue 'police box' to the north of you. It is the about the size of an old phone box. There is a light on the top. The door is open", [Item('Key', "This key opens something")]), + + 'inside': Room("--Console Room--", """It's bigger on the inside!!! There is a large device in the middle with screens and lights and buttons. Go north to look closer. There are also doorways to your left and right.""", [Item('Lantern', 'Use this lantern to light the way ahead')]), + + 'console': Room("--TARDIS Console--", """Description of console""", [Item('Sword', 'It is dangerous to go alone. Take this sword')]), + + 'bedroom': Room("--Bedroom with Bunk Beds--", """The narrow passage bends here from west to north. The smell of gold permeates the air.""", [Item('Coins', 'These coins look like they are worth a lot of money')]), + + 'wardrobe': Room("--Wardrobe--", """You've found the long-lost wardrobe chamber! Sadly, it has already been completely emptied by earlier adventurers. The only exit is to the south.""", [Item('Potion', 'An unknown potion. Use at your own risk')]), + + 'pool': Room("--Swimming Pool--", "", []), + + 'garden': Room("--Garden--", "", []), + 'library': Room("--Library--", """Shhhhhhh.""", [Item('Book', 'Relax and look at this book')]), } # Link rooms together -room['outside'].n_to = room['foyer'] -room['foyer'].s_to = room['outside'] -room['foyer'].n_to = room['overlook'] -room['foyer'].e_to = room['narrow'] -room['overlook'].s_to = room['foyer'] -room['narrow'].w_to = room['foyer'] -room['narrow'].n_to = room['treasure'] -room['treasure'].s_to = room['narrow'] -room['overlook'].w_to = room['library'] -room['library'].e_to = room['overlook'] +room['outside'].n_to = room['inside'] +room['inside'].s_to = room['outside'] +room['inside'].n_to = room['console'] +room['console'].s_to = room['inside'] +room['inside'].e_to = room['bedroom'] +room['bedroom'].w_to = room['inside'] +room['bedroom'].s_to = room['wardrobe'] +room['wardrobe'].n_to = room['bedroom'] +room['console'].w_to = room['library'] +room['library'].e_to = room['console'] # # Main @@ -44,7 +52,7 @@ # * Prints the current description (the textwrap module might be useful here). # * Waits for user input * - dir = input("------------------\nPlease enter a direction... n, s, e, w OR q to quit the game. Press m for more options. \n---------\n").lower() + dir = input("------------------\nPlease enter a direction... n, s, e, w OR q to quit the game. \nPress m for more options. \n---------\n").lower() parsed_dir = dir.lower().split() if len(parsed_dir) is 1: @@ -60,13 +68,13 @@ for i in player.room.items: print("\t" + i.name + ": " + i.description) else: - print("xx--That direction is a dead end.--xx") + print("xx--That direction is a de ad end.--xx") elif dir == "i" or dir == "inventory": print("Inventory:") for item in player.inventory: print("\t" + item.name) elif dir == "m" or dir == "menu": - print("Move North | n \nMove South | s \nMove East | e \nMove West | w \nPick Up Item | get (item name) \n Drop Item | drop (item name) \nInventory | i\nQuit | q") + print("Move North | n \nMove South | s \nMove East | e \nMove West | w \nPick Up Item | get (item name) \nDrop Item | drop (item name) \nInventory | i\nQuit | q") elif dir != "q": print("**Invalid choice. m for options **") From ce6974272ff8cf1f193cc496d7fd79fe6723684b Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Wed, 8 Aug 2018 10:33:24 -0700 Subject: [PATCH 27/52] continued doctor who theme --- src/days-2-4-adv/adv.py | 60 ++++++++++++++++++++++++----------------- 1 file changed, 36 insertions(+), 24 deletions(-) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index 259ca2f8be..3b1ab6adcf 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -5,36 +5,48 @@ # Declare all the rooms room = { - 'outside': Room("--Outside--", "There is a blue 'police box' to the north of you. It is the about the size of an old phone box. There is a light on the top. The door is open", [Item('Key', "This key opens something")]), + 'outside': Room("--Outside--", "There is a blue 'police box' in front of you. It is the about the size of an old telephone booth. There is a light on the top. The door is open.", [Item('Key', "This key opens something")]), - 'inside': Room("--Console Room--", """It's bigger on the inside!!! There is a large device in the middle with screens and lights and buttons. Go north to look closer. There are also doorways to your left and right.""", [Item('Lantern', 'Use this lantern to light the way ahead')]), + 'inside': Room("--Console Room--", """It's bigger on the inside!!! You are in a large room with white circles on the walls. There is a console in front of you. There are doorways to either side.""", [Item('Lantern', 'Use this lantern to light the way ahead.')]), - 'console': Room("--TARDIS Console--", """Description of console""", [Item('Sword', 'It is dangerous to go alone. Take this sword')]), + 'console': Room("--TARDIS Console--", """The console is metal and rolling lights. There are screens and buttons and levers. Do you go forward to push a button or take a step back?""", [Item('Screwdriver', 'It is dangerous to go alone. Take this sonic screwdriver.')]), - 'bedroom': Room("--Bedroom with Bunk Beds--", """The narrow passage bends here from west to north. The smell of gold permeates the air.""", [Item('Coins', 'These coins look like they are worth a lot of money')]), + 'past': Room("--Dinosaurs!?!--", """There is a clunky, whirring noise. The police box shakes. You open the door and see ... dinosaurs!?! And the sky is purple. You did not sign up for this. Go back to safety.""", [Item('Fez', 'How is there a fez in this wild place? You put in on your head - just in case. ')]), - 'wardrobe': Room("--Wardrobe--", """You've found the long-lost wardrobe chamber! Sadly, it has already been completely emptied by -earlier adventurers. The only exit is to the south.""", [Item('Potion', 'An unknown potion. Use at your own risk')]), + 'bedroom': Room("--Bedroom--", """You enter a bedroom with twin-size bunk beds along one wall. It's not exactly the honeymoon suite, but does this mean someone lives in this thing? There is a door in front of you. Do you dare continue on or do you chicken out and go back?""", [Item('Coins', 'These coins look like they are worth a lot of money! $$$')]), - 'pool': Room("--Swimming Pool--", "", []), + 'garden': Room("--Garden--", """You are now deep inside the box and have discovered a garden. There are flowers bigger than your head and some menacing vines swaying back and forth in the still air. Do you go back or check out the door to your left?""", [Item('Potion', 'An unknown potion. Use at your own risk')]), - 'garden': Room("--Garden--", "", []), + 'pool': Room("--Swimming Pool--", """There is a large swimming pool with crystal blue water and floaty toys. There are fluffy towels on lounge chairs on the deck. There is a door in front of you or would you like to go back he way you came?""", [Item('Scarf', 'Who needs a super-long, multi-colored scarf at the pool?')]), - 'library': Room("--Library--", """Shhhhhhh.""", [Item('Book', 'Relax and look at this book')]), + 'library': Room("--Library--", """You walk into a ginormous library filled with millions of books. There is a note tacked to a nearby shelf. It reads: \n'You want weapons? You're in a library. Books are the best weapon in the world. This room's the greatest arsenal you could have. Arm yourself.' \nThere is a doorway to your right and behind you. Or would you like to stay and read a while?""", [Item('Book', 'This book has a metallic cover. You open it up and see a language you don\'t recognize. It was published in the year 8575.')]), } # Link rooms together -room['outside'].n_to = room['inside'] -room['inside'].s_to = room['outside'] -room['inside'].n_to = room['console'] -room['console'].s_to = room['inside'] -room['inside'].e_to = room['bedroom'] -room['bedroom'].w_to = room['inside'] -room['bedroom'].s_to = room['wardrobe'] -room['wardrobe'].n_to = room['bedroom'] -room['console'].w_to = room['library'] -room['library'].e_to = room['console'] +room['outside'].f_to = room['inside'] +room['inside'].b_to = room['outside'] + +room['inside'].f_to = room['console'] +room['console'].b_to = room['inside'] + +room['console'].f_to = room['past'] +room['past'].b_to = room['console'] + +room['inside'].r_to = room['bedroom'] +room['bedroom'].l_to = room['inside'] + +room['library'].r_to = room['inside'] +room['inside'].l_to = room['library'] + +room['library'].b_to = room['pool'] +room['pool'].f_to = room['library'] + +room['bedroom'].f_to = room['garden'] +room['garden'].b_to = room['bedroom'] + +room['garden'].l_to = room['pool'] +room['pool'].r_to = room['garden'] # # Main @@ -52,12 +64,12 @@ # * Prints the current description (the textwrap module might be useful here). # * Waits for user input * - dir = input("------------------\nPlease enter a direction... n, s, e, w OR q to quit the game. \nPress m for more options. \n---------\n").lower() + dir = input("------------------\nPlease enter a direction... f-(forward), b-(backwards), l-(left), r-(right) OR q to quit the game. \nPress m for more options. \n---------\n").lower() parsed_dir = dir.lower().split() if len(parsed_dir) is 1: # directional inputs - if dir == "n" or dir == "e" or dir == "w" or dir == "s": + if dir == "f" or dir == "b" or dir == "l" or dir == "r": if hasattr(player.room, dir + '_to'): player.room = getattr(player.room, dir + '_to') print(player.room, "\n", player.room.description, "\n") @@ -68,13 +80,13 @@ for i in player.room.items: print("\t" + i.name + ": " + i.description) else: - print("xx--That direction is a de ad end.--xx") + print("xx--That direction is a dead end.--xx") elif dir == "i" or dir == "inventory": print("Inventory:") for item in player.inventory: print("\t" + item.name) elif dir == "m" or dir == "menu": - print("Move North | n \nMove South | s \nMove East | e \nMove West | w \nPick Up Item | get (item name) \nDrop Item | drop (item name) \nInventory | i\nQuit | q") + print("Move Forward | f \nMove Backwards | b \nMove Right | r \nMove Left | l \nPick Up Item | get (item name) \nDrop Item | drop (item name) \nInventory | i\nQuit | q") elif dir != "q": print("**Invalid choice. m for options **") @@ -102,7 +114,7 @@ player.inventory.remove(i) # remove item from room inventory player.room.items.append(i) -print("You quit the adventure! :( ") +print("You quit the adventure! You step outside the box. There is a whoop-whoop noise and the box disappears. Maybe some day you will see the box again and can explore further. :( ") "Exit" # If the user enters a cardinal direction, attempt to move to the room there. # Print an error message if the movement isn't allowed. From 9f551da1d8edd15e42b32a21ecad49ded2b398d8 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Wed, 8 Aug 2018 19:44:07 -0700 Subject: [PATCH 28/52] added treasure, score, moved item methods to item --- src/days-2-4-adv/adv.py | 42 ++++++++++++++++++++++---------------- src/days-2-4-adv/item.py | 33 ++++++++++++++++++++++++++++-- src/days-2-4-adv/player.py | 1 + 3 files changed, 56 insertions(+), 20 deletions(-) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index 3b1ab6adcf..201d4fa449 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -1,6 +1,6 @@ from room import Room from player import Player -from item import Item +from item import Item, Treasure # Declare all the rooms @@ -9,17 +9,19 @@ 'inside': Room("--Console Room--", """It's bigger on the inside!!! You are in a large room with white circles on the walls. There is a console in front of you. There are doorways to either side.""", [Item('Lantern', 'Use this lantern to light the way ahead.')]), - 'console': Room("--TARDIS Console--", """The console is metal and rolling lights. There are screens and buttons and levers. Do you go forward to push a button or take a step back?""", [Item('Screwdriver', 'It is dangerous to go alone. Take this sonic screwdriver.')]), + 'console': Room("--TARDIS Console--", """The console is metal and rolling lights. There are screens and buttons and levers. Are you brave enough to push the button on the left or right, or will you take a step back?""", [Item('Screwdriver', 'It is dangerous to go alone. Take this sonic screwdriver.')]), 'past': Room("--Dinosaurs!?!--", """There is a clunky, whirring noise. The police box shakes. You open the door and see ... dinosaurs!?! And the sky is purple. You did not sign up for this. Go back to safety.""", [Item('Fez', 'How is there a fez in this wild place? You put in on your head - just in case. ')]), - 'bedroom': Room("--Bedroom--", """You enter a bedroom with twin-size bunk beds along one wall. It's not exactly the honeymoon suite, but does this mean someone lives in this thing? There is a door in front of you. Do you dare continue on or do you chicken out and go back?""", [Item('Coins', 'These coins look like they are worth a lot of money! $$$')]), + 'future': Room("--Outer Space!!!--", """There is a clunky, whirring noise. The police box shakes. You open the door and see ... a black abyss of stars and planets!?! And there are space ships flying around. You don't have a space suit or the nerve to go out there. Go back to safety.""", [Item('Satsuma', 'There is a satsuma orange floating in space in front of you. You pick it up and put it in your pocket. You\'ll never know when you might need some sustenance.')]), - 'garden': Room("--Garden--", """You are now deep inside the box and have discovered a garden. There are flowers bigger than your head and some menacing vines swaying back and forth in the still air. Do you go back or check out the door to your left?""", [Item('Potion', 'An unknown potion. Use at your own risk')]), + 'bedroom': Room("--Bedroom--", """You enter a bedroom with twin-size bunk beds along one wall. It's not exactly the honeymoon suite, but does this mean someone lives in this thing? There is a door in front of you. Do you dare continue on or do you chicken out and go back?""", [Treasure('Coins', 'These coins are clearly ancient, maybe Roman, but they look so shiny and new. I bet they\'re worth a ton of money.', 500)]), + + 'garden': Room("--Garden--", """You are now deep inside the box and have discovered a garden. There are flowers bigger than your car and some menacing vines swaying back and forth in the still air. Do you go back or check out the door to your left?""", [Item('Potion', 'An unknown potion. Use at your own risk'), Treasure('Diamond', 'A HUGE diamond, crystal clear and sparkly', 1000)]), 'pool': Room("--Swimming Pool--", """There is a large swimming pool with crystal blue water and floaty toys. There are fluffy towels on lounge chairs on the deck. There is a door in front of you or would you like to go back he way you came?""", [Item('Scarf', 'Who needs a super-long, multi-colored scarf at the pool?')]), - 'library': Room("--Library--", """You walk into a ginormous library filled with millions of books. There is a note tacked to a nearby shelf. It reads: \n'You want weapons? You're in a library. Books are the best weapon in the world. This room's the greatest arsenal you could have. Arm yourself.' \nThere is a doorway to your right and behind you. Or would you like to stay and read a while?""", [Item('Book', 'This book has a metallic cover. You open it up and see a language you don\'t recognize. It was published in the year 8575.')]), + 'library': Room("--Library--", """You walk into a ginormous library filled with millions of books. There is a note tacked to a nearby shelf. It reads: \n'You want weapons? You're in a library. Books are the best weapon in the world. This room's the greatest arsenal you could have. Arm yourself.' \nThere is a doorway to your right and behind you. Or would you like to stay and read a while?""", [Item('Book', 'This book has a metallic cover. You open it up and see a language you don\'t recognize. It was published in the year 8575.'), Treasure('Sword', 'A gold, Arthurian sword inlaid with rubies.', 700)],), } # Link rooms together @@ -30,9 +32,12 @@ room['inside'].f_to = room['console'] room['console'].b_to = room['inside'] -room['console'].f_to = room['past'] +room['console'].r_to = room['past'] room['past'].b_to = room['console'] +room['console'].l_to = room['future'] +room['future'].b_to = room['console'] + room['inside'].r_to = room['bedroom'] room['bedroom'].l_to = room['inside'] @@ -63,10 +68,15 @@ # * Prints the current room name # * Prints the current description (the textwrap module might be useful here). # * Waits for user input * + + if player.score >= 1500: + print('You\'re rich. Get out of here and spend your riches. You win!!') + exit() dir = input("------------------\nPlease enter a direction... f-(forward), b-(backwards), l-(left), r-(right) OR q to quit the game. \nPress m for more options. \n---------\n").lower() parsed_dir = dir.lower().split() + if len(parsed_dir) is 1: # directional inputs if dir == "f" or dir == "b" or dir == "l" or dir == "r": @@ -85,8 +95,10 @@ print("Inventory:") for item in player.inventory: print("\t" + item.name) + elif dir == "s" or dir == "score": + print("Score: " + str(player.score)) elif dir == "m" or dir == "menu": - print("Move Forward | f \nMove Backwards | b \nMove Right | r \nMove Left | l \nPick Up Item | get (item name) \nDrop Item | drop (item name) \nInventory | i\nQuit | q") + print("Move Forward | f \nMove Backwards | b \nMove Right | r \nMove Left | l \nPick Up Item | get (item name) \nDrop Item | drop (item name) \nInventory | i \nScore | s\nQuit | q") elif dir != "q": print("**Invalid choice. m for options **") @@ -101,20 +113,14 @@ if action == "g" or action == "get": for i in player.room.items: if parsed_dir[1] == i.name.lower(): - print("Adding item to inventory") - # put item in player inventory - player.inventory.append(i) - # remove item from room inventory - player.room.items.remove(i) + #on_grab item + i.on_grab(player) + elif action == "d" or action == "drop": for i in player.inventory: if parsed_dir[1] == i.name.lower(): - print("Removing item from inventory") - # put item in player inventory - player.inventory.remove(i) - # remove item from room inventory - player.room.items.append(i) -print("You quit the adventure! You step outside the box. There is a whoop-whoop noise and the box disappears. Maybe some day you will see the box again and can explore further. :( ") + i.on_drop(player) +print("You end the adventure! You step outside the box. There is a whoop-whoop noise and the box disappears. Maybe some day you will see the box again and can explore further. :( ") "Exit" # If the user enters a cardinal direction, attempt to move to the room there. # Print an error message if the movement isn't allowed. diff --git a/src/days-2-4-adv/item.py b/src/days-2-4-adv/item.py index b1456eac8c..e6500fa7ac 100644 --- a/src/days-2-4-adv/item.py +++ b/src/days-2-4-adv/item.py @@ -1,6 +1,35 @@ class Item: - def __init__(self, name, description): + def __init__( self, name, description ): self.name = name self.description = description def __repr__(self): - return f"{self.name} : {self.description}" \ No newline at end of file + return f"{self.name} : {self.description}" + + def on_grab(self, player): + print("Adding item to inventory") + # put item in player inventory + player.inventory.append(self) + # remove item from room inventory + player.room.items.remove(self) + + def on_drop(self, player): + print("Removing item from inventory") + # put item in player inventory + player.inventory.remove(self) + # remove item from room inventory + player.room.items.append(self) + +class Treasure( Item ): + def __init__( self, name, description, value ): + super().__init__(name, description) + # Item.__init__(self, name, description) + self.value = value + self.picked_up = False + + def on_grab(self, player): + super().on_grab(player) + if self.picked_up == False: + player.score += self.value + #if not i.picked_up + #update score + self.picked_up = True diff --git a/src/days-2-4-adv/player.py b/src/days-2-4-adv/player.py index 3c10668eb4..2b709bde87 100644 --- a/src/days-2-4-adv/player.py +++ b/src/days-2-4-adv/player.py @@ -5,3 +5,4 @@ def __init__(self, name, room, inventory): self.name = name self.room = room self.inventory = inventory + self.score = 0 From 0f28c876eb2f50999357d494fd18cd39b1ae99f6 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Wed, 8 Aug 2018 19:50:51 -0700 Subject: [PATCH 29/52] added light and drop_light --- src/days-2-4-adv/adv.py | 4 ++-- src/days-2-4-adv/item.py | 11 +++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index 201d4fa449..ef364654bb 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -1,13 +1,13 @@ from room import Room from player import Player -from item import Item, Treasure +from item import Item, Treasure, LightSource # Declare all the rooms room = { 'outside': Room("--Outside--", "There is a blue 'police box' in front of you. It is the about the size of an old telephone booth. There is a light on the top. The door is open.", [Item('Key', "This key opens something")]), - 'inside': Room("--Console Room--", """It's bigger on the inside!!! You are in a large room with white circles on the walls. There is a console in front of you. There are doorways to either side.""", [Item('Lantern', 'Use this lantern to light the way ahead.')]), + 'inside': Room("--Console Room--", """It's bigger on the inside!!! You are in a large room with white circles on the walls. There is a console in front of you. There are doorways to either side.""", [LightSource('Lantern', 'Use this lantern to light the way ahead.')]), 'console': Room("--TARDIS Console--", """The console is metal and rolling lights. There are screens and buttons and levers. Are you brave enough to push the button on the left or right, or will you take a step back?""", [Item('Screwdriver', 'It is dangerous to go alone. Take this sonic screwdriver.')]), diff --git a/src/days-2-4-adv/item.py b/src/days-2-4-adv/item.py index e6500fa7ac..fb7d50046a 100644 --- a/src/days-2-4-adv/item.py +++ b/src/days-2-4-adv/item.py @@ -33,3 +33,14 @@ def on_grab(self, player): #if not i.picked_up #update score self.picked_up = True + +class LightSource( Item ): + def __init__( self, name, description): + super().__init__(name, description) + def on_drop(self, player): + print("Are you sure you want to explore in the dark? Okay, then... \nDrops light.") + # put item in player inventory + player.inventory.remove(self) + # remove item from room inventory + player.room.items.append(self) + From 6cc336b69f110184d742e181f0528b1de9536334 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Wed, 8 Aug 2018 20:26:01 -0700 Subject: [PATCH 30/52] added light-room functionality, need to add if light is in room functionality --- src/days-2-4-adv/adv.py | 33 +++++++++++++++++++-------------- src/days-2-4-adv/item.py | 19 +++++++++++++++---- src/days-2-4-adv/player.py | 1 + src/days-2-4-adv/room.py | 10 ++-------- 4 files changed, 37 insertions(+), 26 deletions(-) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index ef364654bb..9468e38ca2 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -5,23 +5,23 @@ # Declare all the rooms room = { - 'outside': Room("--Outside--", "There is a blue 'police box' in front of you. It is the about the size of an old telephone booth. There is a light on the top. The door is open.", [Item('Key', "This key opens something")]), + 'outside': Room("--Outside--", "There is a blue 'police box' in front of you. It is the about the size of an old telephone booth. There is a light on the top. The door is open.", [Item('Key', "This key opens something")], True), - 'inside': Room("--Console Room--", """It's bigger on the inside!!! You are in a large room with white circles on the walls. There is a console in front of you. There are doorways to either side.""", [LightSource('Lantern', 'Use this lantern to light the way ahead.')]), + 'inside': Room("--Console Room--", """It's bigger on the inside!!! You are in a large room with white circles on the walls. There is a console in front of you. There are doorways to either side.""", [LightSource('Lantern', 'Use this lantern to light the way ahead.')], True), - 'console': Room("--TARDIS Console--", """The console is metal and rolling lights. There are screens and buttons and levers. Are you brave enough to push the button on the left or right, or will you take a step back?""", [Item('Screwdriver', 'It is dangerous to go alone. Take this sonic screwdriver.')]), + 'console': Room("--TARDIS Console--", """The console is metal and rolling lights. There are screens and buttons and levers. Are you brave enough to push the button on the left or right, or will you take a step back?""", [Item('Screwdriver', 'It is dangerous to go alone. Take this sonic screwdriver.')], True), - 'past': Room("--Dinosaurs!?!--", """There is a clunky, whirring noise. The police box shakes. You open the door and see ... dinosaurs!?! And the sky is purple. You did not sign up for this. Go back to safety.""", [Item('Fez', 'How is there a fez in this wild place? You put in on your head - just in case. ')]), + 'past': Room("--Dinosaurs!?!--", """There is a clunky, whirring noise. The police box shakes. You open the door and see ... dinosaurs!?! And the sky is purple. You did not sign up for this. Go back to safety.""", [Item('Fez', 'How is there a fez in this wild place? You put in on your head - just in case. ')], True), - 'future': Room("--Outer Space!!!--", """There is a clunky, whirring noise. The police box shakes. You open the door and see ... a black abyss of stars and planets!?! And there are space ships flying around. You don't have a space suit or the nerve to go out there. Go back to safety.""", [Item('Satsuma', 'There is a satsuma orange floating in space in front of you. You pick it up and put it in your pocket. You\'ll never know when you might need some sustenance.')]), + 'future': Room("--Outer Space!!!--", """There is a clunky, whirring noise. The police box shakes. You open the door and see ... a black abyss of stars and planets!?! And there are space ships flying around. You don't have a space suit or the nerve to go out there. Go back to safety.""", [Item('Satsuma', 'There is a satsuma orange floating in space in front of you. You pick it up and put it in your pocket. You\'ll never know when you might need some sustenance.')], False), - 'bedroom': Room("--Bedroom--", """You enter a bedroom with twin-size bunk beds along one wall. It's not exactly the honeymoon suite, but does this mean someone lives in this thing? There is a door in front of you. Do you dare continue on or do you chicken out and go back?""", [Treasure('Coins', 'These coins are clearly ancient, maybe Roman, but they look so shiny and new. I bet they\'re worth a ton of money.', 500)]), + 'bedroom': Room("--Bedroom--", """You enter a bedroom with twin-size bunk beds along one wall. It's not exactly the honeymoon suite, but does this mean someone lives in this thing? There is a door in front of you. Do you dare continue on or do you chicken out and go back?""", [Treasure('Coins', 'These coins are clearly ancient, maybe Roman, but they look so shiny and new. I bet they\'re worth a ton of money.', 500), LightSource('Flashlight', 'A portable light source that can safely fit in your pocket!')], False), - 'garden': Room("--Garden--", """You are now deep inside the box and have discovered a garden. There are flowers bigger than your car and some menacing vines swaying back and forth in the still air. Do you go back or check out the door to your left?""", [Item('Potion', 'An unknown potion. Use at your own risk'), Treasure('Diamond', 'A HUGE diamond, crystal clear and sparkly', 1000)]), + 'garden': Room("--Garden--", """You are now deep inside the box and have discovered a garden. There are flowers bigger than your car and some menacing vines swaying back and forth in the still air. Do you go back or check out the door to your left?""", [Item('Potion', 'An unknown potion. Use at your own risk'), Treasure('Diamond', 'A HUGE diamond, crystal clear and sparkly', 1000)], False), - 'pool': Room("--Swimming Pool--", """There is a large swimming pool with crystal blue water and floaty toys. There are fluffy towels on lounge chairs on the deck. There is a door in front of you or would you like to go back he way you came?""", [Item('Scarf', 'Who needs a super-long, multi-colored scarf at the pool?')]), + 'pool': Room("--Swimming Pool--", """There is a large swimming pool with crystal blue water and floaty toys. There are fluffy towels on lounge chairs on the deck. There is a door in front of you or would you like to go back he way you came?""", [Item('Scarf', 'Who needs a super-long, multi-colored scarf at the pool?')], True), - 'library': Room("--Library--", """You walk into a ginormous library filled with millions of books. There is a note tacked to a nearby shelf. It reads: \n'You want weapons? You're in a library. Books are the best weapon in the world. This room's the greatest arsenal you could have. Arm yourself.' \nThere is a doorway to your right and behind you. Or would you like to stay and read a while?""", [Item('Book', 'This book has a metallic cover. You open it up and see a language you don\'t recognize. It was published in the year 8575.'), Treasure('Sword', 'A gold, Arthurian sword inlaid with rubies.', 700)],), + 'library': Room("--Library--", """You walk into a ginormous library filled with millions of books. There is a note tacked to a nearby shelf. It reads: \n'You want weapons? You're in a library. Books are the best weapon in the world. This room's the greatest arsenal you could have. Arm yourself.' \nThere is a doorway to your right and behind you. Or would you like to stay and read a while?""", [Item('Book', 'This book has a metallic cover. You open it up and see a language you don\'t recognize. It was published in the year 8575.'), Treasure('Sword', 'A gold, Arthurian sword inlaid with rubies.', 700)], False), } # Link rooms together @@ -83,12 +83,17 @@ if hasattr(player.room, dir + '_to'): player.room = getattr(player.room, dir + '_to') print(player.room, "\n", player.room.description, "\n") - print("Items in this room:") - if len(player.room.items) == 0: - print("none") + if player.room.is_light == True or player.light == True: + print("Items in this room:") + if len(player.room.items) == 0: + print("none") + else: + for i in player.room.items: + print("\t" + i.name + ": " + i.description) + # elif isinstance(player.room.items, LightSource): + # print('Something') else: - for i in player.room.items: - print("\t" + i.name + ": " + i.description) + print("It's pitch black. Good luck finding more items in here.") else: print("xx--That direction is a dead end.--xx") elif dir == "i" or dir == "inventory": diff --git a/src/days-2-4-adv/item.py b/src/days-2-4-adv/item.py index fb7d50046a..a8e6df2623 100644 --- a/src/days-2-4-adv/item.py +++ b/src/days-2-4-adv/item.py @@ -37,10 +37,21 @@ def on_grab(self, player): class LightSource( Item ): def __init__( self, name, description): super().__init__(name, description) - def on_drop(self, player): - print("Are you sure you want to explore in the dark? Okay, then... \nDrops light.") + + def on_grab(self, player): + print("Adding light to inventory") # put item in player inventory - player.inventory.remove(self) + player.inventory.append(self) # remove item from room inventory - player.room.items.append(self) + player.room.items.remove(self) + player.light = True + + def on_drop(self, player): + light = input("Are you sure you want to explore in the dark? Y/N \n") + if light.lower() == "y": + print("Dropping light") + # remove item in player inventory + player.inventory.remove(self) + # add item to room inventory + player.room.items.append(self) diff --git a/src/days-2-4-adv/player.py b/src/days-2-4-adv/player.py index 2b709bde87..e750027d0a 100644 --- a/src/days-2-4-adv/player.py +++ b/src/days-2-4-adv/player.py @@ -6,3 +6,4 @@ def __init__(self, name, room, inventory): self.room = room self.inventory = inventory self.score = 0 + self.light = False diff --git a/src/days-2-4-adv/room.py b/src/days-2-4-adv/room.py index 60f59a904c..c18c592540 100644 --- a/src/days-2-4-adv/room.py +++ b/src/days-2-4-adv/room.py @@ -1,18 +1,12 @@ # Implement a class to hold room information. This should have name and # description attributes. class Room: - def __init__(self, name, description, items): + def __init__(self, name, description, items, is_light): self.name = name self.description = description self.items = items + self.is_light = is_light def __repr__(self): return f"{self.name}" - # def view_items(self): - # print("Items found in this room") - # if len(self.items) == 0: - # print("none") - # else: - # for i in self.items: - # print("\t" + i) From 9b746553dff759931833f6eab2d8f616a6b90a90 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Thu, 9 Aug 2018 10:10:41 -0700 Subject: [PATCH 31/52] isinstance of light in room working --- src/days-2-4-adv/adv.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index 9468e38ca2..40c796e9ad 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -82,16 +82,18 @@ if dir == "f" or dir == "b" or dir == "l" or dir == "r": if hasattr(player.room, dir + '_to'): player.room = getattr(player.room, dir + '_to') - print(player.room, "\n", player.room.description, "\n") + print(player.room, "\n", player.room.description, "\n") + if player.room.is_light == False and player.light == False: + for i in player.room.items: + if isinstance(i, LightSource): + print('It\'s dark in here, but you sense that a light source is near') if player.room.is_light == True or player.light == True: print("Items in this room:") if len(player.room.items) == 0: - print("none") + print("none") else: for i in player.room.items: print("\t" + i.name + ": " + i.description) - # elif isinstance(player.room.items, LightSource): - # print('Something') else: print("It's pitch black. Good luck finding more items in here.") else: From 2e9a158761b4e11600081c2081d44620866a60c6 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Thu, 9 Aug 2018 11:06:48 -0700 Subject: [PATCH 32/52] mvp, all light messages working --- src/days-2-4-adv/adv.py | 35 ++++++++++++----------------------- src/days-2-4-adv/item.py | 32 ++++++++++++++++++++------------ 2 files changed, 32 insertions(+), 35 deletions(-) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index 40c796e9ad..2a851984fc 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -15,7 +15,7 @@ 'future': Room("--Outer Space!!!--", """There is a clunky, whirring noise. The police box shakes. You open the door and see ... a black abyss of stars and planets!?! And there are space ships flying around. You don't have a space suit or the nerve to go out there. Go back to safety.""", [Item('Satsuma', 'There is a satsuma orange floating in space in front of you. You pick it up and put it in your pocket. You\'ll never know when you might need some sustenance.')], False), - 'bedroom': Room("--Bedroom--", """You enter a bedroom with twin-size bunk beds along one wall. It's not exactly the honeymoon suite, but does this mean someone lives in this thing? There is a door in front of you. Do you dare continue on or do you chicken out and go back?""", [Treasure('Coins', 'These coins are clearly ancient, maybe Roman, but they look so shiny and new. I bet they\'re worth a ton of money.', 500), LightSource('Flashlight', 'A portable light source that can safely fit in your pocket!')], False), + 'bedroom': Room("--Bedroom--", """You enter a bedroom with twin-size bunk beds along one wall. It's not exactly the honeymoon suite, but does this mean someone lives in this thing? There is a door in front of you. Do you dare continue on or do you chicken out and go back to the left?""", [Treasure('Coins', 'These coins are clearly ancient, maybe Roman, but they look so shiny and new. I bet they\'re worth a ton of money.', 500), LightSource('Flashlight', 'A portable light source that can safely fit in your pocket!')], False), 'garden': Room("--Garden--", """You are now deep inside the box and have discovered a garden. There are flowers bigger than your car and some menacing vines swaying back and forth in the still air. Do you go back or check out the door to your left?""", [Item('Potion', 'An unknown potion. Use at your own risk'), Treasure('Diamond', 'A HUGE diamond, crystal clear and sparkly', 1000)], False), @@ -56,19 +56,14 @@ # # Main # - -# Make a new player object that is currently in the 'outside' room. name = input('Hello, player. What is your name? ') player = Player( name, room['outside'], [ ]) -print(f"\n***Welcome, {player.name}! Let's begin our adventure: ***\n") +print(f"\n***Welcome, {player.name}! Let's begin our adventure. ***\n") print(player.room, "\n", player.room.description) -# Write a loop that: + while dir != "q" and dir != "quit": -# * Prints the current room name -# * Prints the current description (the textwrap module might be useful here). -# * Waits for user input * - + # win condition if player.score >= 1500: print('You\'re rich. Get out of here and spend your riches. You win!!') exit() @@ -76,26 +71,25 @@ dir = input("------------------\nPlease enter a direction... f-(forward), b-(backwards), l-(left), r-(right) OR q to quit the game. \nPress m for more options. \n---------\n").lower() parsed_dir = dir.lower().split() - if len(parsed_dir) is 1: # directional inputs if dir == "f" or dir == "b" or dir == "l" or dir == "r": if hasattr(player.room, dir + '_to'): player.room = getattr(player.room, dir + '_to') print(player.room, "\n", player.room.description, "\n") - if player.room.is_light == False and player.light == False: - for i in player.room.items: - if isinstance(i, LightSource): - print('It\'s dark in here, but you sense that a light source is near') - if player.room.is_light == True or player.light == True: + if player.room.is_light or player.light: print("Items in this room:") if len(player.room.items) == 0: print("none") else: for i in player.room.items: print("\t" + i.name + ": " + i.description) - else: - print("It's pitch black. Good luck finding more items in here.") + elif not player.room.is_light and not player.light: + for i in player.room.items: + if isinstance(i, LightSource): + print('It\'s dark in here, but you sense that a light source is near') + else: + print("It's very dark in here. You can see the the room, but cannot find any items.") else: print("xx--That direction is a dead end.--xx") elif dir == "i" or dir == "inventory": @@ -108,8 +102,7 @@ print("Move Forward | f \nMove Backwards | b \nMove Right | r \nMove Left | l \nPick Up Item | get (item name) \nDrop Item | drop (item name) \nInventory | i \nScore | s\nQuit | q") elif dir != "q": print("**Invalid choice. m for options **") - - + if len(parsed_dir) > 1: action = parsed_dir[0] item = "" @@ -129,7 +122,3 @@ i.on_drop(player) print("You end the adventure! You step outside the box. There is a whoop-whoop noise and the box disappears. Maybe some day you will see the box again and can explore further. :( ") "Exit" -# If the user enters a cardinal direction, attempt to move to the room there. -# Print an error message if the movement isn't allowed. -# -# If the user enters "q", quit the game. diff --git a/src/days-2-4-adv/item.py b/src/days-2-4-adv/item.py index a8e6df2623..a91ff6c5fe 100644 --- a/src/days-2-4-adv/item.py +++ b/src/days-2-4-adv/item.py @@ -5,12 +5,15 @@ def __init__( self, name, description ): def __repr__(self): return f"{self.name} : {self.description}" - def on_grab(self, player): - print("Adding item to inventory") - # put item in player inventory - player.inventory.append(self) - # remove item from room inventory - player.room.items.remove(self) + def on_grab(self, player): + if player.room.is_light == False and player.light == False: + print('Good luck finding items in the dark. Go to another room and find a light, then try again.') + else: + print("Adding item to inventory") + # put item in player inventory + player.inventory.append(self) + # remove item from room inventory + player.room.items.remove(self) def on_drop(self, player): print("Removing item from inventory") @@ -39,12 +42,16 @@ def __init__( self, name, description): super().__init__(name, description) def on_grab(self, player): - print("Adding light to inventory") - # put item in player inventory - player.inventory.append(self) - # remove item from room inventory - player.room.items.remove(self) - player.light = True + if player.room.is_light == False and player.light == False: + print( + 'Good luck finding that in the dark. Go to another room and find a light, then try again.') + else: + print("Adding light to inventory") + # put item in player inventory + player.inventory.append(self) + # remove item from room inventory + player.room.items.remove(self) + player.light = True def on_drop(self, player): light = input("Are you sure you want to explore in the dark? Y/N \n") @@ -52,6 +59,7 @@ def on_drop(self, player): print("Dropping light") # remove item in player inventory player.inventory.remove(self) + player.light = False # add item to room inventory player.room.items.append(self) From 7be8e23a05c6eace55cc39a2ee638c33f191e50f Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Thu, 9 Aug 2018 19:15:11 -0700 Subject: [PATCH 33/52] cleaned up code, added method if item is not in room, player does not have item --- src/days-2-4-adv/adv.py | 31 ++++++++++++++++++++++--------- src/days-2-4-adv/item.py | 11 +++++------ src/days-2-4-adv/room.py | 3 +-- 3 files changed, 28 insertions(+), 17 deletions(-) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index 2a851984fc..a7a3d72ed1 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -68,7 +68,13 @@ print('You\'re rich. Get out of here and spend your riches. You win!!') exit() - dir = input("------------------\nPlease enter a direction... f-(forward), b-(backwards), l-(left), r-(right) OR q to quit the game. \nPress m for more options. \n---------\n").lower() + dir = input("------------------\nPlease enter a direction... \n" + " F\n" + " |\n" + " L----|----R\n" + " |\n" + " B\n" + " OR q to quit the game. \nPress m for more options. \n---------\n").lower() parsed_dir = dir.lower().split() if len(parsed_dir) is 1: @@ -76,30 +82,34 @@ if dir == "f" or dir == "b" or dir == "l" or dir == "r": if hasattr(player.room, dir + '_to'): player.room = getattr(player.room, dir + '_to') - print(player.room, "\n", player.room.description, "\n") + print(player.room, "\n", player.room.description) if player.room.is_light or player.light: - print("Items in this room:") + print("*Items in this room:*") if len(player.room.items) == 0: print("none") else: for i in player.room.items: - print("\t" + i.name + ": " + i.description) + print(i.name + ": " + i.description) elif not player.room.is_light and not player.light: for i in player.room.items: if isinstance(i, LightSource): - print('It\'s dark in here, but you sense that a light source is near') + print(' It\'s dark in here, but you sense that a light source is near.') else: print("It's very dark in here. You can see the the room, but cannot find any items.") else: print("xx--That direction is a dead end.--xx") + elif dir == "i" or dir == "inventory": print("Inventory:") for item in player.inventory: print("\t" + item.name) + elif dir == "s" or dir == "score": - print("Score: " + str(player.score)) + print("Score: " + str(player.score)) + elif dir == "m" or dir == "menu": - print("Move Forward | f \nMove Backwards | b \nMove Right | r \nMove Left | l \nPick Up Item | get (item name) \nDrop Item | drop (item name) \nInventory | i \nScore | s\nQuit | q") + print("Move Forward | f \nMove Backwards | b \nMove Right | r \nMove Left | l \nPick Up Item | get (item name) \nDrop Item | drop (item name) \nInventory | i \nScore | s\nQuit | q") + elif dir != "q": print("**Invalid choice. m for options **") @@ -115,10 +125,13 @@ if parsed_dir[1] == i.name.lower(): #on_grab item i.on_grab(player) - + elif parsed_dir[1] != i.name.lower(): + print("That item is not in this room.") elif action == "d" or action == "drop": for i in player.inventory: if parsed_dir[1] == i.name.lower(): i.on_drop(player) -print("You end the adventure! You step outside the box. There is a whoop-whoop noise and the box disappears. Maybe some day you will see the box again and can explore further. :( ") + else: + print("You don't have that item.") +print("You end your adventure! You step outside the box. There is a whoop-whoop noise and the box disappears. Maybe some day you will see the box again and can explore further. :( ") "Exit" diff --git a/src/days-2-4-adv/item.py b/src/days-2-4-adv/item.py index a91ff6c5fe..8c39f09f63 100644 --- a/src/days-2-4-adv/item.py +++ b/src/days-2-4-adv/item.py @@ -5,8 +5,8 @@ def __init__( self, name, description ): def __repr__(self): return f"{self.name} : {self.description}" - def on_grab(self, player): - if player.room.is_light == False and player.light == False: + def on_grab(self, player): + if not player.room.is_light and not player.light: print('Good luck finding items in the dark. Go to another room and find a light, then try again.') else: print("Adding item to inventory") @@ -31,7 +31,7 @@ def __init__( self, name, description, value ): def on_grab(self, player): super().on_grab(player) - if self.picked_up == False: + if not self.picked_up: player.score += self.value #if not i.picked_up #update score @@ -42,7 +42,7 @@ def __init__( self, name, description): super().__init__(name, description) def on_grab(self, player): - if player.room.is_light == False and player.light == False: + if not player.room.is_light and not player.light: print( 'Good luck finding that in the dark. Go to another room and find a light, then try again.') else: @@ -61,5 +61,4 @@ def on_drop(self, player): player.inventory.remove(self) player.light = False # add item to room inventory - player.room.items.append(self) - + player.room.items.append(self) \ No newline at end of file diff --git a/src/days-2-4-adv/room.py b/src/days-2-4-adv/room.py index c18c592540..5f25eebf0c 100644 --- a/src/days-2-4-adv/room.py +++ b/src/days-2-4-adv/room.py @@ -8,5 +8,4 @@ def __init__(self, name, description, items, is_light): self.is_light = is_light def __repr__(self): - return f"{self.name}" - + return f"{self.name}" \ No newline at end of file From c1819d2be2625650a26ff8ec9364bb07e3c1f721 Mon Sep 17 00:00:00 2001 From: Lisa Canini Date: Thu, 9 Aug 2018 19:25:43 -0700 Subject: [PATCH 34/52] final commit of class --- src/days-2-4-adv/adv.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py index a7a3d72ed1..881f86426b 100644 --- a/src/days-2-4-adv/adv.py +++ b/src/days-2-4-adv/adv.py @@ -125,13 +125,13 @@ if parsed_dir[1] == i.name.lower(): #on_grab item i.on_grab(player) - elif parsed_dir[1] != i.name.lower(): - print("That item is not in this room.") + if parsed_dir[1] != i.name.lower(): + print("That item is not in this room.") elif action == "d" or action == "drop": for i in player.inventory: if parsed_dir[1] == i.name.lower(): i.on_drop(player) - else: - print("You don't have that item.") + if parsed_dir[1] != player.inventory: + print("You don't have that item.") print("You end your adventure! You step outside the box. There is a whoop-whoop noise and the box disappears. Maybe some day you will see the box again and can explore further. :( ") "Exit" From a1076dde2128f8e41e36714e1355f490670c4239 Mon Sep 17 00:00:00 2001 From: LisaCee Date: Tue, 26 Nov 2019 19:27:10 -0800 Subject: [PATCH 35/52] reset to default, without my answers --- FAQ.md | 618 ++++++++++++++++++++ README.md | 275 ++------- src/00_hello.py | 1 + src/01_bignum.py | 4 + src/02_datatypes.py | 21 + src/03_modules.py | 31 + src/{day-1-toy/printf.py => 04_printing.py} | 10 +- src/{day-1-toy/lists.py => 05_lists.py} | 18 +- src/06_tuples.py | 44 ++ src/{day-1-toy/slice.py => 07_slices.py} | 25 +- src/08_comprehensions.py | 41 ++ src/09_dictionaries.py | 44 ++ src/10_functions.py | 12 + src/11_args.py | 63 ++ src/{day-1-toy/scope.py => 12_scopes.py} | 5 +- src/13_file_io.py | 18 + src/14_cal.py | 24 + src/15_classes.py | 29 + src/day-1-toy/args.py | 71 --- src/day-1-toy/bar.txt | 1 - src/day-1-toy/bignum.py | 2 - src/day-1-toy/cal.py | 34 -- src/day-1-toy/comp.py | 32 - src/day-1-toy/datatypes.py | 8 - src/day-1-toy/dicts.py | 34 -- src/day-1-toy/fileio.py | 16 - src/day-1-toy/func.py | 12 - src/day-1-toy/hello.py | 2 - src/day-1-toy/modules.py | 31 - src/day-1-toy/obj.py | 38 -- src/day-1-toy/tuples.py | 34 -- src/days-2-4-adv/adv.py | 137 ----- src/days-2-4-adv/item.py | 64 -- src/days-2-4-adv/player.py | 9 - src/days-2-4-adv/room.py | 11 - src/{day-1-toy => }/foo.txt | 0 src/python-example/history | 1 - src/python-example/history.txt | 1 - src/python-example/rock_paper_scissors | 76 --- src/python-example/rock_paper_scissors.py | 79 --- 40 files changed, 1024 insertions(+), 952 deletions(-) create mode 100644 FAQ.md create mode 100644 src/00_hello.py create mode 100644 src/01_bignum.py create mode 100644 src/02_datatypes.py create mode 100644 src/03_modules.py rename src/{day-1-toy/printf.py => 04_printing.py} (52%) rename src/{day-1-toy/lists.py => 05_lists.py} (67%) create mode 100644 src/06_tuples.py rename src/{day-1-toy/slice.py => 07_slices.py} (52%) create mode 100644 src/08_comprehensions.py create mode 100644 src/09_dictionaries.py create mode 100644 src/10_functions.py create mode 100644 src/11_args.py rename src/{day-1-toy/scope.py => 12_scopes.py} (89%) create mode 100644 src/13_file_io.py create mode 100644 src/14_cal.py create mode 100644 src/15_classes.py delete mode 100644 src/day-1-toy/args.py delete mode 100644 src/day-1-toy/bar.txt delete mode 100644 src/day-1-toy/bignum.py delete mode 100644 src/day-1-toy/cal.py delete mode 100644 src/day-1-toy/comp.py delete mode 100644 src/day-1-toy/datatypes.py delete mode 100644 src/day-1-toy/dicts.py delete mode 100644 src/day-1-toy/fileio.py delete mode 100644 src/day-1-toy/func.py delete mode 100644 src/day-1-toy/hello.py delete mode 100644 src/day-1-toy/modules.py delete mode 100644 src/day-1-toy/obj.py delete mode 100644 src/day-1-toy/tuples.py delete mode 100644 src/days-2-4-adv/adv.py delete mode 100644 src/days-2-4-adv/item.py delete mode 100644 src/days-2-4-adv/player.py delete mode 100644 src/days-2-4-adv/room.py rename src/{day-1-toy => }/foo.txt (100%) delete mode 100644 src/python-example/history delete mode 100644 src/python-example/history.txt delete mode 100644 src/python-example/rock_paper_scissors delete mode 100644 src/python-example/rock_paper_scissors.py diff --git a/FAQ.md b/FAQ.md new file mode 100644 index 0000000000..cbdac517b2 --- /dev/null +++ b/FAQ.md @@ -0,0 +1,618 @@ +# FAQ + + + +## Contents + +### General CS + +* [What are some things we can do to prepare for CS?](#q100) +* [What are some ways to learn a new language?](#q3600) +* [Why test code frequently?](#q3700) +* [Why isn't official documentation more helpful than Stack Overflow?](#q3800) +* [During an interview, what do I do if I can't remember the exact syntax?](#q3900) + +### General Python + +* [In regard to the code challenge solution, why is the '+' operator being used to concatenate strings? I thought we were supposed to use the join() method in Python?](#q300) +* [How do you get out of the Python built-in `help`?](#q400) +* [Are there any helpful VS Code extensions that are recommend for using with Python?](#q500) +* [I'm on Windows; what command do I use to run Python?](#q600) +* [What version of Python do I need?](#q700) +* [How do I get out of the Python REPL?](#q900) +* [What does "REPL" mean?](#q1000) +* [I'm on a Mac and when I run Python it says I'm on version 2.7. Why?](#q1100) +* [Does Python use tabs or spaces?](#q1200) +* [Can you use boolean shortcut assignments?](#q1700) +* [Can you do anonymous functions?](#q1800) +* [What are all those method names with double underscores around them?](#q2000) +* [Where are good Python docs?](#q2600) +* [Which linter?](#q2700) +* [What's the difference between __repr__ and __str__?](#q3300) +* [How does `sys.argv` work?](#q3400) + +### Pipenv + +* [Do I need to use pipenv?](#q800) +* [When do we run pipenv shell?](#q2200) +* [How do I get out of the pipenv shell?](#q2300) +* [How do I install additional packages from pipenv?](#q2400) +* [Is it possible to use system-wide packages from inside the virtual environment?](#q2500) + +### Object-Oriented Programming + +* [Why is there such a debate between OOP and functional programming, and why should we care?](#q200) +* [Following this flow: 1) class Dog is created with attributes size and weight. 2) New instance called Snoopy of class Dog is created. 3) Class Dog gets the method bark() dynamically added to it. Question: will Snoopy now have access to bark() method?](#q2900) +* [Can you dynamically add new methods/properties to class through other functions? Or must all properties/methods be declared at once?](#q2800) +* [If a subclass inherits from two superclasses with a method of the same name, which method will the subclass use?](#q3000) +* [How to handle multiple inheritance and why/when to do it in the first place?](#q3100) + +### Python Scoping + +* [Does Python have hoisting?](#q1400) +* [Does scoping work similar to other languages?](#q1500) +* [Can you return a reference to a function from another function? Or store it in a variable?](#q1600) +* [Can you do anonymous functions?](#q1800) + +### Types + +* [How do I convert an iterator into a list?](#q1300) +* [Is a dict like a JavaScript object?](#q1900) +* [How do I get a value from a dict?](#q2100) +* [Why use tuples instead of lists?](#q3200) +* [How do I concatenate two arrays into a single array?](#q3500) + +## Questions + + +### What are some things we can do to prepare for CS? + +* [CS Wiki](https://github.com/LambdaSchool/CS-Wiki/wiki) +* [Polya's Problem Solving Techniques](https://github.com/LambdaSchool/CS-Wiki/wiki/Polya%27s-Problem-Solving-Techniques) +* [Solving Programming Problems](https://github.com/LambdaSchool/CS-Wiki/wiki/Solving-Programming-Problems) +* [CS Reading List](https://github.com/LambdaSchool/CS-Wiki/wiki/Computer-Science-Reading-List) +* [How to Google effectively](https://github.com/LambdaSchool/CS-Wiki/wiki/How-to-Google-Effectively) +* [How to read specs and code](https://github.com/LambdaSchool/CS-Wiki/wiki/How-to-Read-Specifications-and-Code) +* [Command line primer](https://github.com/LambdaSchool/CS-Wiki/wiki/Command-Line-Primer) +* [Coding style guidelines](https://github.com/LambdaSchool/CS-Wiki/wiki/CS-Coding-Style-Guidelines) + +------------------------------------------------------------------------ + + +### Why is there such a debate between OOP and functional programming, and why should we care? + +There are a lot of [programming +paradigms](https://en.wikipedia.org/wiki/Programming_paradigm) and they all have +their strengths and weaknesses when it comes to solving different types of +problems. + +People can be quite opinionated about their favorites, but it's important to +remember that no one language or paradigm is the right tool for all jobs. And, +additionally, that virtually all problems can be solved in any of the +declarative or imperative paradigms. (Some might produce cleaner, more elegant +code for a particular problem.) + +Paradigms are the hardest thing to learn because you often have to take all the +knowledge you have about solving a problem in another paradigm and throw it out +the window. You have to learn new patterns and techniques to be effective. + +But we encourage this kind of learning because most popular languages are to +some degree _multi-paradigm_, and the more techniques you know from more +paradigms, the more effective you are in that multi-paradigm langage. + +------------------------------------------------------------------------ + + +### In regard to the code challenge solution, why is the '+' operator being used to concatenate strings? I thought we were supposed to use the join() method in Python? + +Using `join()` to join large numbers of strings is definitely faster in Python +than using the `+` operator to do it. The reason is that every time you `join()` +or use the `+` operator, a new string is created. So if you only have to +`join()` once, versus using `+` hundreds of times, you'll run faster. + +That said, if you want to use the `join()` approach, you'll have to have all +your strings in a list, which uses more memory than just having the two or three +that you need at a time to use `+`. So there's a tradeoff. + +Another tradeoff might be in readability. It might be easier to read the `+` +version. That's worth something. + +Finally, if `+` is fast enough for this case, it might not be worth the time to +bother with making a list of strings to `join()`. + +* [Speed comparison with different ways of concatenating strings](https://waymoot.org/home/python_string/) + +------------------------------------------------------------------------ + + +### How do you get out of the Python built-in `help`? + +Hit `q` for "quit". + +It's a common command in Unix "pagers" (programs that show documents a page at a +time). + +------------------------------------------------------------------------ + + +### Are there any helpful VS Code extensions that are recommend for using with Python? + +* [Official VS Code Python Extension](https://code.visualstudio.com/docs/languages/python) + +------------------------------------------------------------------------ + + +### I'm on Windows; what command do I use to run Python? + +If you're running in PowerShell or cmd, use: + +``` +py +``` + +If in bash, use `python` or `python3`. + +------------------------------------------------------------------------ + + +### What version of Python do I need? + +You should have version 3.7 or higher. Test with: + +```shell +python --version +``` + +------------------------------------------------------------------------ + + +### Do I need to use pipenv? + +You should. Good Python devs know how. + +------------------------------------------------------------------------ + + +### How do I get out of the Python REPL? + +Hit `CTRL-D`. This is the way End-Of-File is signified in Unix-likes. + +------------------------------------------------------------------------ + + +### What does "REPL" mean? + +_Read, Evaluate, Print Loop_. + +It reads your input, evaluates it, and prints the result. And loops. + +------------------------------------------------------------------------ + + +### I'm on a Mac and when I run Python it says I'm on version 2.7. Why? + +Macs come with version 2.7 by default. You'll need to install version 3. + +And preferable use `pipenv` after that. + +------------------------------------------------------------------------ + + +### Does Python use tabs or spaces? + +[PEP 8](https://www.python.org/dev/peps/pep-0008/) says four spaces. + +------------------------------------------------------------------------ + + +### How do I convert an iterator into a list? + +Cast it: + +```python +list(range(5)) +``` + +produces: + +```python +[0, 1, 2, 3, 4] +``` + +------------------------------------------------------------------------ + + +### Does Python have hoisting? + +No. + +* [What is hoisting?](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting) + +------------------------------------------------------------------------ + + +### Does scoping work similar to other languages? + +Generally, and also not really. Variables are either global or function-local. + +Since there are no declarations, there's no block-level scope. + +It is similar to `var` in JavaScript. + +------------------------------------------------------------------------ + + +### Can you return a reference to a function from another function? Or store it in a variable? + +Yes. Functions are [first-class citizens](https://en.wikipedia.org/wiki/First-class_citizen). + +------------------------------------------------------------------------ + + +### Can you use boolean shortcut assignments? + +Yes, you can. This is common in Perl and JavaScript, but it's not particularly [idiomatic](https://en.wikipedia.org/wiki/Programming_idiom) in Python. + +```python +x = SomethingFalsey or 5 +``` + +------------------------------------------------------------------------ + + +### Can you do anonymous functions? + +You can use `lambda` for simple functions: + +```python +adder = lambda x, y: x + y + +adder(4, 5) # 9 + +do_some_math(4, 5, lambda x, y: y - x) +``` + +------------------------------------------------------------------------ + + +### Is a dict like a JavaScript object? + +Sort of. + +The syntax is different, though. In Python you must use `[]` notation to access elements. And you must use `"` around the key names. + +------------------------------------------------------------------------ + + +### What are all those method names with double underscores around them? + +Those are function you typically don't need to use, but can override or call if you wish. + +Most commonly used are: + +* `__init__()` is the constructor for objects +* `__str__()` returns a string representation of the object +* `__repr__()` returns a string representation of the object, for debugging + +------------------------------------------------------------------------ + + +### How do I get a value from a dict? + +```python +d = { + "a": 2, + "b": 3 +} + +print(d["a"]) +``` + +You don't use dot notation. + +------------------------------------------------------------------------ + + +### When do we run pipenv shell? + +`pipenv shell` puts you into your work environment. When you're ready to work, or run the code, or install new dependencies, you should be in your pipenv shell. + +------------------------------------------------------------------------ + + +### How do I get out of the pipenv shell? + +Type `exit`. + +------------------------------------------------------------------------ + + +### How do I install additional packages from pipenv? + +```shell +pipenv install packagename +``` + +------------------------------------------------------------------------ + + +### Is it possible to use system-wide packages from inside the virtual environment? + +This is [not recommended](https://pipenv.readthedocs.io/en/latest/diagnose/#no-module-named-module-name). + +------------------------------------------------------------------------ + + +### Where are good Python docs? + +* [Official documentation](https://docs.python.org/3/) tutorial and library reference. + +The official docs might be hard to read at first, but you'll get used to them +quickly + +------------------------------------------------------------------------ + + +### Which linter? + +Pylint or Flake8. The latter seems to be a bit more popular. + +------------------------------------------------------------------------ + + +### Can you dynamically add new methods/properties to class through other functions? Or must all properties/methods be declared at once? + +You can add them dynamically at runtime, but you have to add them to the class itself: + +```python +class Foo(): + pass + +f = Foo() + +Foo.x = 12 # Dynamically add property to class + +f.x == 12 # True! + +def a_method(self): + print("Hi") + +Foo.hi = a_method # Dynamically add method to class + +f.hi() # Prints "Hi" +``` + +This is not a common thing to see in Python, however. + +------------------------------------------------------------------------ + + +### Following this flow: 1) class Dog is created with attributes size and weight. 2) New instance called Snoopy of class Dog is created. 3) Class Dog gets the method bark() dynamically added to it. Question: will Snoopy now have access to bark() method? + +Yes. + +------------------------------------------------------------------------ + + +### If a subclass inherits from two superclasses with a method of the same name, which method will the subclass use? + +The answer to this is twofold: + +1. Lots of devs and shops frown on multiple inheritance, so maybe just don't do + it. + ([Discussion](https://softwareengineering.stackexchange.com/questions/218458/is-there-any-real-reason-multiple-inheritance-is-hated)) + +2. As for the order in which methods of the same name are resolved, check out + the [MRO Algorithm](https://en.wikipedia.org/wiki/C3_linearization) which is + what Python uses. + + +------------------------------------------------------------------------ + + +### How to handle multiple inheritance and why/when to do it in the first place? + +```python +class Base1: + pass + +class Base2: + pass + +class Derived(Base1, Base2): # Multiple inheritance + pass +``` + +Sometimes multiple inheritance can lead to elegant solutions when a subclass +needs attributes from multiple, otherwise-unrelated parent classes. + +However, [a lot of people find it's not worth the +trouble](https://softwareengineering.stackexchange.com/questions/218458/is-there-any-real-reason-multiple-inheritance-is-hated)) +and opt for other solutions, like composition. + +------------------------------------------------------------------------ + + +### Why use tuples instead of lists? + +* Tuples are immutable. There's a school of thought that says bugs can be reduced if you make as many things immutable as you can. +* Tuples are faster than lists to access. +* Some tuples (containing primitive types), can be used as `dict` keys. + +------------------------------------------------------------------------ + + +### What's the difference between __repr__ and __str__? + +Generally speaking, `__repr__` is the string a dev would want to see if they +dumped an object to the screen. `__str__` is the string a user would want to see +if the object were `print()`ed. + +The output of `__repr__` should be _valid Python code that can reproduce the +object_. + +```python +class Goat: + def __init__(self, leg_count): + self.leg_count = leg_count + + def __repr__(self): + return f'Goat(leg_count={self.leg_count})' + + def __str__(self): + return f'a goat with {self.leg_count} legs' +``` + +In action: + +```python +>>> g = Goat(4) +>>> str(g) +'a goat with 4 legs' +>>> g +Goat(leg_count=4) +>>> Goat(leg_count=4) # output of __repr__ makes a clone of that object! +Goat(leg_count=4) +``` + +------------------------------------------------------------------------ + + +### How does `sys.argv` work? + +It's a list that holds _command line arguments_. This is a way for a user to run +your program and specify different behavior from the command line. + +Here's a small program that prints the command line arguments: + +```python +import sys + +for i in range(len(sys.argv)): + print(f'Argument #{i} is: {sys.argv[i]}') +``` + +and here's some output, assuming you named the script `foo.py`: + +```screen +$ python foo.py +Argument #0 is: foo.py +``` + +```screen +$ python foo.py antelope buffalo +Argument #0 is: foo.py +Argument #1 is: antelope +Argument #2 is: buffalo +``` + +Note that the 0th element in the list is the name of the program. + +Here's another program that prints up to whatever number the user specifies: + +```python +import sys + +for i in range(int(sys.argv[1])): + print(i+1) +``` + +Example runs: + +```screen +$ python foo.py 2 +1 +2 +``` + +```screen +$ python foo.py 4 +1 +2 +3 +4 +``` + +------------------------------------------------------------------------ + + +### How do I concatenate two arrays into a single array? + +Use `extend()`. + +```python +a = [1, 2, 3] +b = [4, 5, 6] + +a.extend(b) + +print(a) # [ 1, 2, 3, 4, 5, 6 ] +``` + +------------------------------------------------------------------------ + + +### What are some ways to learn a new language? + +* Figure out how variables and functions work. +* Build small toy programs to test individual features. +* Build a larger project that exercises many features. +* Don't get frustrated! Treat the problem like a curiosity, a thing to be studied. +* Do small tutorials or code-alongs. +* Find docs you like. +* Learn the differences between this language and one you know. +* Learn this language's way of doing the things you know. + +Things to look for in the new language: + +* Collections (arrays, vectors, dictionaries) +* Data types +* Iterators +* Flow control (if, while, loops, etc) +* Functions +* etc. + +------------------------------------------------------------------------ + + +### Why test code frequently? + +It's often better to make progress in small increments than to write a bunch of +stuff and test it in one go. + +Also, it's easier to stay motivated if you spend 10 minutes getting a first +version going, even if it's missing 99% of its features, and then starting to +iterate on that. + +------------------------------------------------------------------------ + + +### Why isn't official documentation more helpful than Stack Overflow? + +Often official documentation is more geared toward being a concise reference. +Stack Overflow is more of an example-based learning environment. + +Sometimes you need to know the specific details. In those cases, you can dig +into the spec, with all it's lawyerly language, and try to decipher what it is +you have to do. + +Other times, you just need a getting-started example, and Stack Overflow is +great for that. + +Both types of documentation have their purpose. + +------------------------------------------------------------------------ + + +### During an interview, what do I do if I can't remember the exact syntax? + +Just say so. + +"I can't remember how to add an element to the end of the list in Python... is +it `push()`? In any case, we'll call the function here that does that." + +(Turns out it's `append()` in Python, but being honest and describing what it is +your're trying to do will get you 99% of the way there in an interview.) diff --git a/README.md b/README.md index 400b72d43e..f54d2b3343 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,4 @@ -# Intro to Python - -## Goals +# Intro to Python I It's time to learn a new language! Python! @@ -57,254 +55,59 @@ best for learning new languages. You can exit the virtual environment by typing `exit`. -## Day 1 - -### Goals +## Goals * Learn the basic syntax and structure of Python -### Summary - -* Implement a number of tiny Python programs that demonstrate Python syntax. +## Summary -### Instructions +* Implement a number of tiny Python programs that demonstrate Python syntax and + language concepts. -Take a look in the `src/` directory. +## Instructions -NOTE: `adv/` is for Day 2, so ignore it for today. +Each directory inside the `src/` directory presents exercises revolving around a +particular concept in Python. Not all of these concepts are unique to Python (in +fact, most probably aren't). This means that you can leverage knowledge you've +obtained via exposure to other programming languages towards learning Python. -Suggested order for implementing the toy programs: +The suggested order for going through each of the directories is: * `hello` -- Hello world * `bignum` -- Print some big numbers * `datatypes` -- Experiment with type conversion * `modules` -- Learn to import from modules -* `printf` -- Formatted print output +* `printing` -- Formatted print output * `lists` -- Python's version of arrays * `tuples` -- Immutable lists typically for heterogenous data -* `slice` -- Accessing parts of lists -* `comp` -- List comprehensions -* `dicts` -- Dictionaries -* `func` -- Functions +* `slices` -- Accessing parts of lists +* `comprehensions` -- List comprehensions +* `dictionaries` -- Dictionaries +* `functions` -- Functions * `args` -- Arguments and Keyword Arguments -* `scope` -- Global, Local, and Non-Local scope -* `fileio` -- Read and write from files -* `cal` -- Experiment with module imports -* `obj` -- Classes and objects - -## Day 2 - -### Goals - -* Solidify the Python basics - - -### Summary - -* Implement a basic text adventure game -* Add classes for rooms and the player -* Add a simple parser that reads user input and performs actions - -### Instructions - -This is in `src/adv/`. Check it out! - -* Put the Room class in room.py based on what you see in `adv.py`. - -* Put the Player class in `player.py`. - -* Follow the instructions `adv.py`. - -* Figure out what all those `.pyc` files are that appear after you successfully - run the program. - -## Day 3 - -### Goals - -* Prepare for more OOP techniques -* Practice classes and lists - -### Summary - -* Add items to the game that the user can carry around -* Make rooms able to hold multiple items -* Make the player able to carry multiple items -* Add two-word commands to the parser -* Add the `get` and `drop` commands to the parser - -### Instructions - -* Add an `Item` class in a file `item.py`. - - * This will be the _base class_ for specialized item types to be declared - later. - - * The item should have `name` and `description` attributes. - - * Hint: the name should be one word for ease in parsing later. - -* Add capability to add items to rooms. - - * The `Room` class should be extended with a `list` that holds the `Item`s - that are currently in that room. - - * Add functionality to the main loop that prints out all the items that are - visible to the player when they are in that room. - -* Add capability to add `Item`s to the player's inventory. The inventory can - also be a `list` of items "in" the player, similar to how `Item`s can be in a - `Room`. - -* Add a new type of sentence the parser can understand: two words. - - * Until now, the parser could just understand one sentence form: - - `verb` - - such as "n" or "q". - - * But now we want to add the form: - - `verb` `object` - - such as "take coins" or "drop sword". - - * Split the entered command and see if it has 1 or 2 words in it to determine - if it's the first or second form. - -* Implement support for the verb `get` followed by an `Item` name. This will be - used to pick up `Item`s. - - * If the user enters `get` or `take` followed by an `Item` name, look at the - contents of the current `Room` to see if the item is there. - - * If it is there, remove it from the `Room` contents, and add it to the - `Player` contents. - - * If it's not there, print an error message telling the user so. - -* Implement support for the verb `drop` followed by an `Item` name. This is the - opposite of `get`/`take`. - -* Add the `i` and `inventory` commands that both show a list of items currently - carried by the player. - -## Day 4 - -### Goals - -* Practice inheritance -* Practice method overriding -* Be able to call superclass methods -* Implement a callback/event structure - -### Summary - -* Add scoring -* Subclass items into treasures -* Subclass items into light sources -* Add methods to notify items when they are picked up or dropped -* Add light and darkness to the game - -### Instructions - -* Add a `score` to your `Player` class. Set it to 0. - -* Add a single word command, `score`, that the user can type in to see their - current score. - -* Add a subclass to `Item` called `Treasure`. - - * The `Treasure` constructor should accept a name, description, and value. - -* During world creation, add three `Treasure`s to convenient `Room`s. - -* Add an `on_take` method to `Item`. - - * Call this method when the `Item` is picked up by the player. - - * The `Item` can use this to run additional code when it is picked up. - -* Override `on_take` in `Treasure` so that the player gets the value of the - `Treasure` added to their `score` attribute _but only the first time the - treasure is picked up_. - - * If the treasure is dropped and picked up again later, the player should - _not_ have the value added to their score again. - -* Add an `on_drop` method to `Item`. Implement it similar to `on_take`. - -* Add a subclass to `Item` called `LightSource`. - -* During world creation, add a `lamp` `LightSource` to a convenient `Room`. - -* Override `on_drop` in `LightSource` that tells the player "It's not wise to - drop your source of light!" if the player drops it. (But still lets them drop - it.) - -* Add an attribute to `Room` called `is_light` that is `True` if the `Room` is - naturally illuminated, or `False` if a `LightSource` is required to see what - is in the room. - -* Modify the main loop to test if there is light in the `Room` (i.e. if - `is_light` is `True` **or** there is a `LightSource` item in the `Room`'s - contents **or** if there is a `LightSource` item in the `Player`'s contents). - - * If there is light in the room, display name, description, and contents as - normal. - - * If there isn't, print out "It's pitch black!" instead. - - * Hint: `isinstance` might help you figure out if there's a `LightSource` - among all the nearby `Item`s. - -* Modify the `get`/`take` code to print "Good luck finding that in the dark!" if - the user tries to pick up an `Item` in the dark. +* `scopes` -- Global, Local, and Non-Local scope +* `file_io` -- Read and write from files +* `cal` -- Experiment with module imports and implement a text-based calendar +* `classes` -- Classes and objects ## Stretch Goals -In arbitrary order: - -* Add more rooms. - -* Add more items to the game. - -* Add a way to win. - -* Add more to the parser. - - * Remember the last `Item` mentioned and substitute that if the user types - "it" later, e.g. - - ``` - take sword - drop it - ``` - - * Add `Item`s with adjectives, like "rusty sword" and "silver sword". - - * Modify the parser to handle commands like "take rusty sword" as well as - "take sword". - - * If the user is in a room that contains both the rusty sword _and_ silver - sword, and they type "take sword", the parser should say, "I don't know - which you mean: rusty sword or silver sword." - -* Modify the code that calls `on_take` to check the return value. If `on_take` - returns `False`, then don't continue picking up the object. (I.e. prevent the - user from picking it up.) - - * This enables you to add logic to `on_take` to code things like "don't allow - the user to pick up the dirt unless they're holding the shovel. - -* Add monsters. - -* Add the `attack` verb that allows you to specify a monster to attack. - -* Add an `on_attack` method to the monster class. - -* Similar to the `on_take` return value modification, above, have `on_attack` - prevent the attack from succeeding unless the user possesses a `sword` item. - -* Come up with more stretch goals! The sky's the limit! +1. One of Python's main philosophical tenets is its emphasis on readability. To + that end, the Python community has standardized around a style guide called + [PEP 8](https://www.python.org/dev/peps/pep-0008/). Take a look at it and + then go over the code you've written and make sure it adheres to what PEP 8 + recommends. Alternatively, PEP 8 linters exist for most code editors (you can + find instructions on installing a Python linter for VSCode + [here](https://code.visualstudio.com/docs/python/linting)). Try installing + one for your editor! + +2. Rewrite code challenges you've solved before or projects you've implemented + before in a different language in Python. Start getting in as much practice + with the language as possible! + +3. Write a program to determine if a number, given on the command line, is prime. + + 1. How can you optimize this program? + 2. Implement [The Sieve of + Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes), one + of the oldest algorithms known (ca. 200 BC). diff --git a/src/00_hello.py b/src/00_hello.py new file mode 100644 index 0000000000..268998dfc7 --- /dev/null +++ b/src/00_hello.py @@ -0,0 +1 @@ +# Print "Hello, world!" to your terminal \ No newline at end of file diff --git a/src/01_bignum.py b/src/01_bignum.py new file mode 100644 index 0000000000..c020928d63 --- /dev/null +++ b/src/01_bignum.py @@ -0,0 +1,4 @@ +# Print out 2 to the 65536 power +# (try doing the same thing in the JS console and see what it outputs) + +# YOUR CODE HERE \ No newline at end of file diff --git a/src/02_datatypes.py b/src/02_datatypes.py new file mode 100644 index 0000000000..54178a241e --- /dev/null +++ b/src/02_datatypes.py @@ -0,0 +1,21 @@ +""" +Python is a strongly-typed language under the hood, which means +that the types of values matter, especially when we're trying +to perform operations on them. + +Note that if you try running the following code without making any +changes, you'll get a TypeError saying you can't perform an operation +on a string and an integer. +""" + +x = 5 +y = "7" + +# Write a print statement that combines x + y into the integer value 12 + +# YOUR CODE HERE + + +# Write a print statement that combines x + y into the string value 57 + +# YOUR CODE HERE \ No newline at end of file diff --git a/src/03_modules.py b/src/03_modules.py new file mode 100644 index 0000000000..97eba053c7 --- /dev/null +++ b/src/03_modules.py @@ -0,0 +1,31 @@ +""" +In this exercise, you'll be playing around with the sys module, +which allows you to access many system specific variables and +methods, and the os module, which gives you access to lower- +level operating system functionality. +""" + +import sys +# See docs for the sys module: https://docs.python.org/3.7/library/sys.html + +# Print out the command line arguments in sys.argv, one per line: +# YOUR CODE HERE + +# Print out the OS platform you're using: +# YOUR CODE HERE + +# Print out the version of Python you're using: +# YOUR CODE HERE + + +import os +# See the docs for the OS module: https://docs.python.org/3.7/library/os.html + +# Print the current process ID +# YOUR CODE HERE + +# Print the current working directory (cwd): +# YOUR CODE HERE + +# Print out your machine's login name +# YOUR CODE HERE diff --git a/src/day-1-toy/printf.py b/src/04_printing.py similarity index 52% rename from src/day-1-toy/printf.py rename to src/04_printing.py index 4d5d75b5ee..06aaa7ff16 100644 --- a/src/day-1-toy/printf.py +++ b/src/04_printing.py @@ -1,3 +1,9 @@ +""" +Python provides a number of ways to perform printing. Research +how to print using the printf operator, the `format` string +method, and by using f-strings. +""" + x = 10 y = 2.24552 z = "I like turtles!" @@ -5,7 +11,7 @@ # Using the printf operator (%), print the following feeding in the values of x, # y, and z: # x is 10, y is 2.25, z is "I like turtles!" -print(f'x is {x}, y is {round(y, 2)}, z is "{z}"') # Use the 'format' string method to print the same thing -print('x is %d, y is %.2f, z is "%s"' % (x, y, z)) + +# Finally, print the same thing using an f-string \ No newline at end of file diff --git a/src/day-1-toy/lists.py b/src/05_lists.py similarity index 67% rename from src/day-1-toy/lists.py rename to src/05_lists.py index a2157e817d..6b7d307182 100644 --- a/src/day-1-toy/lists.py +++ b/src/05_lists.py @@ -7,27 +7,23 @@ # For the following, DO NOT USE AN ASSIGNMENT (=). # Change x so that it is [1, 2, 3, 4] -x.append(4) +# YOUR CODE HERE print(x) # Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10] -x += y -# x.extend(y) +# YOUR CODE HERE print(x) # Change x so that it is [1, 2, 3, 4, 9, 10] -x.remove(8) +# YOUR CODE HERE print(x) # Change x so that it is [1, 2, 3, 4, 9, 99, 10] -x.insert(5, 99) -# x.insert(-1, 99) +# YOUR CODE HERE print(x) # Print the length of list x -# [command here] -print(len(x)) +# YOUR CODE HERE -# Using a for loop, print all the element values multiplied by 1000 -for el in x: - print(el * 1000) \ No newline at end of file +# Print all the values in x multiplied by 1000 +# YOUR CODE HERE \ No newline at end of file diff --git a/src/06_tuples.py b/src/06_tuples.py new file mode 100644 index 0000000000..016e540801 --- /dev/null +++ b/src/06_tuples.py @@ -0,0 +1,44 @@ +""" +Python tuples are sort of like lists, except they're immutable and +are usually used to hold heterogenous data, as opposed to lists +which are typically used to hold homogenous data. Tuples use +parens instead of square brackets. + +More specifically, tuples are faster than lists. If you're looking +to just define a constant set of values and that set of values +never needs to be mutated, use a tuple instead of a list. + +Additionally, your code will be safer if you opt to "write-protect" +data that does not need to be changed. Tuples enforce immutability +automatically. +""" + +# Example: + +import math + +def dist(a, b): + """Compute the distance between two x,y points.""" + x0, y0 = a # Destructuring assignment + x1, y1 = b + + return math.sqrt((x1 - x0)**2 + (y1 - y0)**2) + +a = (2, 7) # <-- x,y coordinates stored in tuples +b = (-14, 72) + +# Prints "Distance is 66.94" +print("Distance is: {:.2f}".format(dist(a, b))) + + + +# Write a function `print_tuple` that prints all the values in a tuple + +# YOUR CODE HERE + +t = (1, 2, 5, 7, 99) +print_tuple(t) # Prints 1 2 5 7 99, one per line + +# Declare a tuple of 1 element then print it +u = (1) # What needs to be added to make this work? +print_tuple(u) diff --git a/src/day-1-toy/slice.py b/src/07_slices.py similarity index 52% rename from src/day-1-toy/slice.py rename to src/07_slices.py index 7d835b5ed9..5e0b3bd8ee 100644 --- a/src/day-1-toy/slice.py +++ b/src/07_slices.py @@ -1,26 +1,37 @@ +""" +Python exposes a terse and intuitive syntax for performing +slicing on lists and strings. This makes it easy to reference +only a portion of a list or string. + +This Stack Overflow answer provides a brief but thorough +overview: https://stackoverflow.com/a/509295 + +Use Python's slice syntax to achieve the following: +""" + a = [2, 4, 1, 7, 9, 6] # Output the second element: 4: -print(a[1]) +print() # Output the second-to-last element: 9 -print(a[-2]) +print() # Output the last three elements in the array: [7, 9, 6] -print(a[(len(a)-3): ]) +print() # Output the two middle elements in the array: [1, 7] -print(a[2 : 4]) +print() # Output every element except the first one: [4, 1, 7, 9, 6] -print(a[1:]) +print() # Output every element except the last one: [2, 4, 1, 7, 9] -print(a[:(len(a)-1)]) +print() # For string s... s = "Hello, world!" # Output just the 8th-12th characters: "world" -print(s[7:12]) \ No newline at end of file +print() \ No newline at end of file diff --git a/src/08_comprehensions.py b/src/08_comprehensions.py new file mode 100644 index 0000000000..67eb742e50 --- /dev/null +++ b/src/08_comprehensions.py @@ -0,0 +1,41 @@ +""" +List comprehensions are one cool and unique feature of Python. +They essentially act as a terse and concise way of initializing +and populating a list given some expression that specifies how +the list should be populated. + +Take a look at https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions +for more info regarding list comprehensions. +""" + +# Write a list comprehension to produce the array [1, 2, 3, 4, 5] + +y = [] + +print (y) + +# Write a list comprehension to produce the cubes of the numbers 0-9: +# [0, 1, 8, 27, 64, 125, 216, 343, 512, 729] + +y = [] + +print(y) + +# Write a list comprehension to produce the uppercase version of all the +# elements in array a. Hint: "foo".upper() is "FOO". + +a = ["foo", "bar", "baz"] + +y = [] + +print(y) + +# Use a list comprehension to create a list containing only the _even_ elements +# the user entered into list x. + +x = input("Enter comma-separated numbers: ").split(',') + +# What do you need between the square brackets to make it work? +y = [] + +print(y) \ No newline at end of file diff --git a/src/09_dictionaries.py b/src/09_dictionaries.py new file mode 100644 index 0000000000..687a2ae2dc --- /dev/null +++ b/src/09_dictionaries.py @@ -0,0 +1,44 @@ +""" +Dictionaries are Python's implementation of associative arrays. +There's not much different with Python's version compared to what +you'll find in other languages (though you can also initialize and +populate dictionaries using comprehensions just like you can with +lists!). + +The docs can be found here: +https://docs.python.org/3/tutorial/datastructures.html#dictionaries + +For this exercise, you have a list of dictionaries. Each dictionary +has the following keys: + - lat: a signed integer representing a latitude value + - lon: a signed integer representing a longitude value + - name: a name string for this location +""" + +waypoints = [ + { + "lat": 43, + "lon": -121, + "name": "a place" + }, + { + "lat": 41, + "lon": -123, + "name": "another place" + }, + { + "lat": 43, + "lon": -122, + "name": "a third place" + } +] + +# Add a new waypoint to the list +# YOUR CODE HERE + +# Modify the dictionary with name "a place" such that its longitude +# value is -130 and change its name to "not a real place" +# YOUR CODE HERE + +# Write a loop that prints out all the field values for all the waypoints +# YOUR CODE HERE \ No newline at end of file diff --git a/src/10_functions.py b/src/10_functions.py new file mode 100644 index 0000000000..5830100c2c --- /dev/null +++ b/src/10_functions.py @@ -0,0 +1,12 @@ +# Write a function is_even that will return true if the passed-in number is even. + +# YOUR CODE HERE + +# Read a number from the keyboard +num = input("Enter a number: ") +num = int(num) + +# Print out "Even!" if the number is even. Otherwise print "Odd" + +# YOUR CODE HERE + diff --git a/src/11_args.py b/src/11_args.py new file mode 100644 index 0000000000..b23783d530 --- /dev/null +++ b/src/11_args.py @@ -0,0 +1,63 @@ +# Experiment with positional arguments, arbitrary arguments, and keyword +# arguments. + +# Write a function f1 that takes two integer positional arguments and returns +# the sum. This is what you'd consider to be a regular, normal function. + +# YOUR CODE HERE + +print(f1(1, 2)) + +# Write a function f2 that takes any number of integer arguments and prints the +# sum. Google for "python arbitrary arguments" and look for "*args" + +# YOUR CODE HERE + +print(f2(1)) # Should print 1 +print(f2(1, 3)) # Should print 4 +print(f2(1, 4, -12)) # Should print -7 +print(f2(7, 9, 1, 3, 4, 9, 0)) # Should print 33 + +a = [7, 6, 5, 4] + +# What thing do you have to add to make this work? +print(f2(a)) # Should print 22 + +# Write a function f3 that accepts either one or two arguments. If one argument, +# it returns that value plus 1. If two arguments, it returns the sum of the +# arguments. Google "python default arguments" for a hint. + +# YOUR CODE HERE + +print(f3(1, 2)) # Should print 3 +print(f3(8)) # Should print 9 + + +# Write a function f4 that accepts an arbitrary number of keyword arguments and +# prints out the keys and values like so: +# +# key: foo, value: bar +# key: baz, value: 12 +# +# Google "python keyword arguments". + +# YOUR CODE HERE + +# Should print +# key: a, value: 12 +# key: b, value: 30 +f4(a=12, b=30) + +# Should print +# key: city, value: Berkeley +# key: population, value: 121240 +# key: founded, value: "March 23, 1868" +f4(city="Berkeley", population=121240, founded="March 23, 1868") + +d = { + "monster": "goblin", + "hp": 3 +} + +# What thing do you have to add to make this work? +f4(d) \ No newline at end of file diff --git a/src/day-1-toy/scope.py b/src/12_scopes.py similarity index 89% rename from src/day-1-toy/scope.py rename to src/12_scopes.py index 7d1efb608e..339ae1915e 100644 --- a/src/day-1-toy/scope.py +++ b/src/12_scopes.py @@ -1,11 +1,10 @@ -# Experiment with scope in Python. +# Experiment with scopes in Python. # Good reading: https://www.programiz.com/python-programming/global-local-nonlocal-variables # When you use a variable in a function, it's local in scope to the function. x = 12 def changeX(): - global x x = 99 changeX() @@ -20,7 +19,6 @@ def outer(): y = 120 def inner(): - nonlocal y y = 999 inner() @@ -28,4 +26,5 @@ def inner(): # This prints 120. What do we have to change in inner() to get it to print # 999? Google "python nested function scope". print(y) + outer() \ No newline at end of file diff --git a/src/13_file_io.py b/src/13_file_io.py new file mode 100644 index 0000000000..f0ddeb0020 --- /dev/null +++ b/src/13_file_io.py @@ -0,0 +1,18 @@ +""" +Python makes performing file I/O simple. Take a look +at how to read and write to files here: + +https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files +""" + +# Open up the "foo.txt" file (which already exists) for reading +# Print all the contents of the file, then close the file + +# YOUR CODE HERE + +# Open up a file called "bar.txt" (which doesn't exist yet) for +# writing. Write three lines of arbitrary content to that file, +# then close the file. Open up "bar.txt" and inspect it to make +# sure that it contains what you expect it to contain + +# YOUR CODE HERE \ No newline at end of file diff --git a/src/14_cal.py b/src/14_cal.py new file mode 100644 index 0000000000..26010fa008 --- /dev/null +++ b/src/14_cal.py @@ -0,0 +1,24 @@ +""" +The Python standard library's 'calendar' module allows you to +render a calendar to your terminal. +https://docs.python.org/3.6/library/calendar.html + +Write a program that accepts user input of the form + `14_cal.py month [year]` +and does the following: + - If the user doesn't specify any input, your program should + print the calendar for the current month. The 'datetime' + module may be helpful for this. + - If the user specifies one argument, assume they passed in a + month and render the calendar for that month of the current year. + - If the user specifies two arguments, assume they passed in + both the month and the year. Render the calendar for that + month and year. + - Otherwise, print a usage statement to the terminal indicating + the format that your program expects arguments to be given. + Then exit the program. +""" + +import sys +import calendar +from datetime import datetime \ No newline at end of file diff --git a/src/15_classes.py b/src/15_classes.py new file mode 100644 index 0000000000..e4425325cd --- /dev/null +++ b/src/15_classes.py @@ -0,0 +1,29 @@ +# Make a class LatLon that can be passed parameters `lat` and `lon` to the +# constructor + +# YOUR CODE HERE + +# Make a class Waypoint that can be passed parameters `name`, `lat`, and `lon` to the +# constructor. It should inherit from LatLon. Look up the `super` method. + +# YOUR CODE HERE + +# Make a class Geocache that can be passed parameters `name`, `difficulty`, +# `size`, `lat`, and `lon` to the constructor. What should it inherit from? + +# YOUR CODE HERE + +# Make a new waypoint and print it out: "Catacombs", 41.70505, -121.51521 + +# YOUR CODE HERE + +# Without changing the following line, how can you make it print into something +# more human-readable? Hint: Look up the `object.__str__` method +print(waypoint) + +# Make a new geocache "Newberry Views", diff 1.5, size 2, 44.052137, -121.41556 + +# YOUR CODE HERE + +# Print it--also make this print more nicely +print(geocache) diff --git a/src/day-1-toy/args.py b/src/day-1-toy/args.py deleted file mode 100644 index 1344a011bf..0000000000 --- a/src/day-1-toy/args.py +++ /dev/null @@ -1,71 +0,0 @@ -# Experiment with positional arguments, arbitrary arguments, and keyword -# arguments. - -# Write a function f1 that takes two integer positional arguments and returns -# the sum. This is what you'd consider to be a regular, normal function. - -def f1(a, b): - return a + b - -print(f1(1, 2)) - -# Write a function f2 that takes any number of iteger arguments and prints the -# sum. Google for "python arbitrary arguments" and look for "*args" - -def f2(*args): - return sum(args) - -print(f2(1)) # Should print 1 -print(f2(1, 3)) # Should print 4 -print(f2(1, 4, -12)) # Should print -7 -print(f2(7, 9, 1, 3, 4, 9, 0)) # Should print 33 - -a = [7, 6, 5, 4] - -# # What thing do you have to add to make this work? -print(f2(*a)) # Should print 22 - -# # Write a function f3 that accepts either one or two arguments. If one argument, -# # it returns that value plus 1. If two arguments, it returns the sum of the -# # arguments. Google "python default arguments" for a hint. - -def f3(arg, arg2=None): - if arg2 is None: - return arg + 1 - else: - return arg + arg2 - -print(f3(1, 2)) # Should print 3 -print(f3(8)) # Should print 9 - - -# # Write a function f4 that accepts an arbitrary number of keyword arguments and -# # prints ouf the keys and values like so: -# # -# # key: foo, value: bar -# # key: baz, value: 12 -# # -# # Google "python keyword arguments". - -def f4(*args, **kwargs): - for key, value in kwargs.items(): - print(f'key: {key}, value: {value}') - -# # Should print -# # key: a, value: 12 -# # key: b, value: 30 -f4(a=12, b=30) - -# # Should print -# # key: city, value: Berkeley -# # key: population, value: 121240 -# # key: founded, value: "March 23, 1868" -f4(city="Berkeley", population=121240, founded="March 23, 1868") - -d = { - "monster": "goblin", - "hp": 3 -} - -# # What thing do you have to add to make this work? -f4(**d) \ No newline at end of file diff --git a/src/day-1-toy/bar.txt b/src/day-1-toy/bar.txt deleted file mode 100644 index 01a25e0ac6..0000000000 --- a/src/day-1-toy/bar.txt +++ /dev/null @@ -1 +0,0 @@ -Quarrel, sir? No, sir. \ No newline at end of file diff --git a/src/day-1-toy/bignum.py b/src/day-1-toy/bignum.py deleted file mode 100644 index 865465b440..0000000000 --- a/src/day-1-toy/bignum.py +++ /dev/null @@ -1,2 +0,0 @@ -# Print out 2 to the 65536 power -print(pow(2, 65536)) \ No newline at end of file diff --git a/src/day-1-toy/cal.py b/src/day-1-toy/cal.py deleted file mode 100644 index 5fed4ad0d5..0000000000 --- a/src/day-1-toy/cal.py +++ /dev/null @@ -1,34 +0,0 @@ -# Use the 'calendar' module to draw calendars to the console -# https://docs.python.org/3.6/library/calendar.html -# -# Use the sys module to look for command line arguments in the `argv` list -# variable. -# -# If the user specifies two command line arguments, month and year, then draw -# the calendar for that month. - -# Stretch goal: if the user doesn't specify anything on the command line, show -# the calendar for the current month. See the 'datetime' module. - -# Hint: this should be about 15 lines of code. No loops are required. Read the -# docs for the calendar module closely. - -import sys -import calendar -import datetime - -# month = int(input("Enter a month 1 - 12: ")) -# year = int(input("Enter a 4 digit year: ")) - -month = sys.argv[1] -year = sys.argv[2] - -# if month == None: -# month = 8 -# if year == None: -# year = 2018 - -c = calendar.TextCalendar(calendar.SUNDAY) -str = c.formatmonth(int(year), int(month)) -print(str) - diff --git a/src/day-1-toy/comp.py b/src/day-1-toy/comp.py deleted file mode 100644 index edb9f086b4..0000000000 --- a/src/day-1-toy/comp.py +++ /dev/null @@ -1,32 +0,0 @@ -# Write a list comprehension to produce the array [1, 2, 3, 4, 5] - -y = [i for i in range(1, 6)] - -print (y) - -# Write a list comprehension to produce the cubes of the numbers 0-9: -# [0, 1, 8, 27, 64, 125, 216, 343, 512, 729] - -y = [i**3 for i in range(0, 10)] - -print(y) - -# Write a list comprehension to produce the uppercase version of all the -# elements in array a. Hint: "foo".upper() is "FOO". - -a = ["foo", "bar", "baz"] - -y = [item.upper() for item in a] - -print(y) - -# # Use a list comprehension to create a list containing only the _even_ elements -# # the user entered into list x. - -x = input("Enter comma-separated numbers: ").split(',') - -# # What do you need between the square brackets to make it work? -y = [i for i in x if int(i) % 2 == 0] - -print(y) - diff --git a/src/day-1-toy/datatypes.py b/src/day-1-toy/datatypes.py deleted file mode 100644 index b8c6f50a05..0000000000 --- a/src/day-1-toy/datatypes.py +++ /dev/null @@ -1,8 +0,0 @@ -x = 5 -y = "7" - -# Write a print statement that combines x + y into the integer value 12 -print(x + (int(y))) - -# Write a print statement that combines x + y into the string value 57 -print((str(x)) + y) \ No newline at end of file diff --git a/src/day-1-toy/dicts.py b/src/day-1-toy/dicts.py deleted file mode 100644 index 402bbf630c..0000000000 --- a/src/day-1-toy/dicts.py +++ /dev/null @@ -1,34 +0,0 @@ -# Make an array of dictionaries. Each dictionary should have keys: -# -# lat: the latitude -# lon: the longitude -# name: the waypoint name -# -# Make up three entries of various values. - -waypoints = [ - { - "lat": 43, - "lon": -121, - "name": "a place" - }, - { - "lat": 41, - "lon": -123, - "name": "another place" - }, - { - "lat": 43, - "lon": -122, - "name": "a third place" - } -] - -# Write a loop that prints out all the field values for all the waypoints -for i in waypoints: - print(i) -# Add a new waypoint to the list -waypoints.append({"lat": 42, "lon": 42, "name": "Somewhere"}) - -for i in waypoints: - print(i) diff --git a/src/day-1-toy/fileio.py b/src/day-1-toy/fileio.py deleted file mode 100644 index 1c096caa6d..0000000000 --- a/src/day-1-toy/fileio.py +++ /dev/null @@ -1,16 +0,0 @@ -# Use open to open file "foo.txt" for reading -file = open('foo.txt', 'r') -# Print all the lines in the file -for line in file: - print(line) -# Close the file -file.close() - -# Use open to open file "bar.txt" for writing -file = open('bar.txt', 'w') -# Use the write() method to write three lines to the file -file.write(line) -file.write(line) -file.write(line) -# Close the file -file.close() \ No newline at end of file diff --git a/src/day-1-toy/func.py b/src/day-1-toy/func.py deleted file mode 100644 index 6b8e12bf81..0000000000 --- a/src/day-1-toy/func.py +++ /dev/null @@ -1,12 +0,0 @@ -# Write a function is_even that will return true if the passed in number is even. -def is_even(n): - return n % 2 == 0 - -# print(is_even(5)) -# Read a number from the keyboard -num = input("Enter a number: ") -if int(num) % 2 == 0: - print('Even!') -else: - print('Odd') -# Print out "Even!" if the number is even. Otherwise print "Odd" \ No newline at end of file diff --git a/src/day-1-toy/hello.py b/src/day-1-toy/hello.py deleted file mode 100644 index 6ee1f01872..0000000000 --- a/src/day-1-toy/hello.py +++ /dev/null @@ -1,2 +0,0 @@ -# Write Hello, world -print('Hello, world') \ No newline at end of file diff --git a/src/day-1-toy/modules.py b/src/day-1-toy/modules.py deleted file mode 100644 index a354afebfc..0000000000 --- a/src/day-1-toy/modules.py +++ /dev/null @@ -1,31 +0,0 @@ -import sys -import os - -# Module "sys" -# -# See docs for the sys module: https://docs.python.org/3.7/library/sys.html - -# Print out the command line arguments in sys.argv, one per line: -print(sys.argv) - -# Print out the platform from sys: -print(sys.platform) - -# Print out the Python version from sys: -print(sys.version) - - - -# Module "os" -# -# See the docs for the OS module: https://docs.python.org/3.7/library/os.html - -# Print the current process ID -print(os.getpid()) - -# Print the current working directory (cwd): -print(os.getcwd()) - -# Print your login name -print(os.getlogin()) - diff --git a/src/day-1-toy/obj.py b/src/day-1-toy/obj.py deleted file mode 100644 index 44f8bce352..0000000000 --- a/src/day-1-toy/obj.py +++ /dev/null @@ -1,38 +0,0 @@ -# Make a class LatLon that can be passed parameters `lat` and `lon` to the -# constructor -class LatLon: - def __init__(self, lat, lon): - self.lat = lat - self.lon = lon -# Make a class Waypoint that can be passed parameters `name`, `lat`, and `lon` to the -# constructor. It should inherit from LatLon. -class Waypoint(LatLon): - def __init__(self, name, lat, lon): - LatLon.__init__(self, lat, lon) - self.name = name - def __str__(self): - return f"Waypoint: {self.name}, {self.lat}, {self.lon}" - - -# Make a class Geocache that can be passed parameters `name`, `difficulty`, -# `size`, `lat`, and `lon` to the constructor. What should it inherit from? -class Geocache(Waypoint): - def __init__(self, name, difficulty, size, lat, lon): - super().__init__(name, lat, lon) - self.difficulty = difficulty - self.size = size - def __repr__(self): - return f"Geocache: {self.name}, {self.difficulty}, {self.size}, {self.lat}, {self.lon}" -# Make a new waypoint "Catacombs", 41.70505, -121.51521 -w = Waypoint("Catacombs", 41.70505, -121.51521) - -# Print it -print(w) -# Without changing the following line, how can you make it print into something -# more human-readable? -# print(w) - -# Make a new geocache "Newberry Views", diff 1.5, size 2, 44.052137, -121.41556 -g = Geocache("Newberry Views", 1.5, 2, 44.052137, -121.41556) -# Print it--also make this print more nicely -print(g) diff --git a/src/day-1-toy/tuples.py b/src/day-1-toy/tuples.py deleted file mode 100644 index cd15f9f0f5..0000000000 --- a/src/day-1-toy/tuples.py +++ /dev/null @@ -1,34 +0,0 @@ -# Tuples are like lists, but are immutable and are usually used to hold -# heterogenous data. They use parens instead of square brackets. - -# Example: - -import math - -def dist(a, b): - """Compute the distance between two x,y points.""" - x0, y0 = a # Destructuring assignment - x1, y1 = b - - return math.sqrt((x1 - x0)**2 + (y1 - y0)**2) - -a = (2, 7) # <-- x,y coordinates stored in tuples -b = (-14, 72) - -# Prints "Distance is 66.94" -print("Distance is: {:.2f}".format(dist(a, b))) - - - -# Write a function that prints all the values in a tuple - -def print_tuple(t): - for item in t: - print(item) - -t = (1, 2, 5, 7, 99) -print_tuple(t) # Prints 1 2 5 7 99, one per line - -# # Declare a tuple of 1 element then print it -u = (1,) # What needs to be added to make this work? -print_tuple(u) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py deleted file mode 100644 index 881f86426b..0000000000 --- a/src/days-2-4-adv/adv.py +++ /dev/null @@ -1,137 +0,0 @@ -from room import Room -from player import Player -from item import Item, Treasure, LightSource - -# Declare all the rooms - -room = { - 'outside': Room("--Outside--", "There is a blue 'police box' in front of you. It is the about the size of an old telephone booth. There is a light on the top. The door is open.", [Item('Key', "This key opens something")], True), - - 'inside': Room("--Console Room--", """It's bigger on the inside!!! You are in a large room with white circles on the walls. There is a console in front of you. There are doorways to either side.""", [LightSource('Lantern', 'Use this lantern to light the way ahead.')], True), - - 'console': Room("--TARDIS Console--", """The console is metal and rolling lights. There are screens and buttons and levers. Are you brave enough to push the button on the left or right, or will you take a step back?""", [Item('Screwdriver', 'It is dangerous to go alone. Take this sonic screwdriver.')], True), - - 'past': Room("--Dinosaurs!?!--", """There is a clunky, whirring noise. The police box shakes. You open the door and see ... dinosaurs!?! And the sky is purple. You did not sign up for this. Go back to safety.""", [Item('Fez', 'How is there a fez in this wild place? You put in on your head - just in case. ')], True), - - 'future': Room("--Outer Space!!!--", """There is a clunky, whirring noise. The police box shakes. You open the door and see ... a black abyss of stars and planets!?! And there are space ships flying around. You don't have a space suit or the nerve to go out there. Go back to safety.""", [Item('Satsuma', 'There is a satsuma orange floating in space in front of you. You pick it up and put it in your pocket. You\'ll never know when you might need some sustenance.')], False), - - 'bedroom': Room("--Bedroom--", """You enter a bedroom with twin-size bunk beds along one wall. It's not exactly the honeymoon suite, but does this mean someone lives in this thing? There is a door in front of you. Do you dare continue on or do you chicken out and go back to the left?""", [Treasure('Coins', 'These coins are clearly ancient, maybe Roman, but they look so shiny and new. I bet they\'re worth a ton of money.', 500), LightSource('Flashlight', 'A portable light source that can safely fit in your pocket!')], False), - - 'garden': Room("--Garden--", """You are now deep inside the box and have discovered a garden. There are flowers bigger than your car and some menacing vines swaying back and forth in the still air. Do you go back or check out the door to your left?""", [Item('Potion', 'An unknown potion. Use at your own risk'), Treasure('Diamond', 'A HUGE diamond, crystal clear and sparkly', 1000)], False), - - 'pool': Room("--Swimming Pool--", """There is a large swimming pool with crystal blue water and floaty toys. There are fluffy towels on lounge chairs on the deck. There is a door in front of you or would you like to go back he way you came?""", [Item('Scarf', 'Who needs a super-long, multi-colored scarf at the pool?')], True), - - 'library': Room("--Library--", """You walk into a ginormous library filled with millions of books. There is a note tacked to a nearby shelf. It reads: \n'You want weapons? You're in a library. Books are the best weapon in the world. This room's the greatest arsenal you could have. Arm yourself.' \nThere is a doorway to your right and behind you. Or would you like to stay and read a while?""", [Item('Book', 'This book has a metallic cover. You open it up and see a language you don\'t recognize. It was published in the year 8575.'), Treasure('Sword', 'A gold, Arthurian sword inlaid with rubies.', 700)], False), -} - -# Link rooms together - -room['outside'].f_to = room['inside'] -room['inside'].b_to = room['outside'] - -room['inside'].f_to = room['console'] -room['console'].b_to = room['inside'] - -room['console'].r_to = room['past'] -room['past'].b_to = room['console'] - -room['console'].l_to = room['future'] -room['future'].b_to = room['console'] - -room['inside'].r_to = room['bedroom'] -room['bedroom'].l_to = room['inside'] - -room['library'].r_to = room['inside'] -room['inside'].l_to = room['library'] - -room['library'].b_to = room['pool'] -room['pool'].f_to = room['library'] - -room['bedroom'].f_to = room['garden'] -room['garden'].b_to = room['bedroom'] - -room['garden'].l_to = room['pool'] -room['pool'].r_to = room['garden'] - -# -# Main -# -name = input('Hello, player. What is your name? ') -player = Player( name, room['outside'], [ ]) - -print(f"\n***Welcome, {player.name}! Let's begin our adventure. ***\n") -print(player.room, "\n", player.room.description) - -while dir != "q" and dir != "quit": - # win condition - if player.score >= 1500: - print('You\'re rich. Get out of here and spend your riches. You win!!') - exit() - - dir = input("------------------\nPlease enter a direction... \n" - " F\n" - " |\n" - " L----|----R\n" - " |\n" - " B\n" - " OR q to quit the game. \nPress m for more options. \n---------\n").lower() - parsed_dir = dir.lower().split() - - if len(parsed_dir) is 1: - # directional inputs - if dir == "f" or dir == "b" or dir == "l" or dir == "r": - if hasattr(player.room, dir + '_to'): - player.room = getattr(player.room, dir + '_to') - print(player.room, "\n", player.room.description) - if player.room.is_light or player.light: - print("*Items in this room:*") - if len(player.room.items) == 0: - print("none") - else: - for i in player.room.items: - print(i.name + ": " + i.description) - elif not player.room.is_light and not player.light: - for i in player.room.items: - if isinstance(i, LightSource): - print(' It\'s dark in here, but you sense that a light source is near.') - else: - print("It's very dark in here. You can see the the room, but cannot find any items.") - else: - print("xx--That direction is a dead end.--xx") - - elif dir == "i" or dir == "inventory": - print("Inventory:") - for item in player.inventory: - print("\t" + item.name) - - elif dir == "s" or dir == "score": - print("Score: " + str(player.score)) - - elif dir == "m" or dir == "menu": - print("Move Forward | f \nMove Backwards | b \nMove Right | r \nMove Left | l \nPick Up Item | get (item name) \nDrop Item | drop (item name) \nInventory | i \nScore | s\nQuit | q") - - elif dir != "q": - print("**Invalid choice. m for options **") - - if len(parsed_dir) > 1: - action = parsed_dir[0] - item = "" - for i in range(1, len(parsed_dir)): - item += parsed_dir[i] + ' ' - item = item.strip() - - if action == "g" or action == "get": - for i in player.room.items: - if parsed_dir[1] == i.name.lower(): - #on_grab item - i.on_grab(player) - if parsed_dir[1] != i.name.lower(): - print("That item is not in this room.") - elif action == "d" or action == "drop": - for i in player.inventory: - if parsed_dir[1] == i.name.lower(): - i.on_drop(player) - if parsed_dir[1] != player.inventory: - print("You don't have that item.") -print("You end your adventure! You step outside the box. There is a whoop-whoop noise and the box disappears. Maybe some day you will see the box again and can explore further. :( ") -"Exit" diff --git a/src/days-2-4-adv/item.py b/src/days-2-4-adv/item.py deleted file mode 100644 index 8c39f09f63..0000000000 --- a/src/days-2-4-adv/item.py +++ /dev/null @@ -1,64 +0,0 @@ -class Item: - def __init__( self, name, description ): - self.name = name - self.description = description - def __repr__(self): - return f"{self.name} : {self.description}" - - def on_grab(self, player): - if not player.room.is_light and not player.light: - print('Good luck finding items in the dark. Go to another room and find a light, then try again.') - else: - print("Adding item to inventory") - # put item in player inventory - player.inventory.append(self) - # remove item from room inventory - player.room.items.remove(self) - - def on_drop(self, player): - print("Removing item from inventory") - # put item in player inventory - player.inventory.remove(self) - # remove item from room inventory - player.room.items.append(self) - -class Treasure( Item ): - def __init__( self, name, description, value ): - super().__init__(name, description) - # Item.__init__(self, name, description) - self.value = value - self.picked_up = False - - def on_grab(self, player): - super().on_grab(player) - if not self.picked_up: - player.score += self.value - #if not i.picked_up - #update score - self.picked_up = True - -class LightSource( Item ): - def __init__( self, name, description): - super().__init__(name, description) - - def on_grab(self, player): - if not player.room.is_light and not player.light: - print( - 'Good luck finding that in the dark. Go to another room and find a light, then try again.') - else: - print("Adding light to inventory") - # put item in player inventory - player.inventory.append(self) - # remove item from room inventory - player.room.items.remove(self) - player.light = True - - def on_drop(self, player): - light = input("Are you sure you want to explore in the dark? Y/N \n") - if light.lower() == "y": - print("Dropping light") - # remove item in player inventory - player.inventory.remove(self) - player.light = False - # add item to room inventory - player.room.items.append(self) \ No newline at end of file diff --git a/src/days-2-4-adv/player.py b/src/days-2-4-adv/player.py deleted file mode 100644 index e750027d0a..0000000000 --- a/src/days-2-4-adv/player.py +++ /dev/null @@ -1,9 +0,0 @@ -# Write a class to hold player information, e.g. what room they are in -# currently. -class Player: - def __init__(self, name, room, inventory): - self.name = name - self.room = room - self.inventory = inventory - self.score = 0 - self.light = False diff --git a/src/days-2-4-adv/room.py b/src/days-2-4-adv/room.py deleted file mode 100644 index 5f25eebf0c..0000000000 --- a/src/days-2-4-adv/room.py +++ /dev/null @@ -1,11 +0,0 @@ -# Implement a class to hold room information. This should have name and -# description attributes. -class Room: - def __init__(self, name, description, items, is_light): - self.name = name - self.description = description - self.items = items - self.is_light = is_light - - def __repr__(self): - return f"{self.name}" \ No newline at end of file diff --git a/src/day-1-toy/foo.txt b/src/foo.txt similarity index 100% rename from src/day-1-toy/foo.txt rename to src/foo.txt diff --git a/src/python-example/history b/src/python-example/history deleted file mode 100644 index d9e0850ae2..0000000000 --- a/src/python-example/history +++ /dev/null @@ -1 +0,0 @@ -0, 0, 0 \ No newline at end of file diff --git a/src/python-example/history.txt b/src/python-example/history.txt deleted file mode 100644 index aa178b017c..0000000000 --- a/src/python-example/history.txt +++ /dev/null @@ -1 +0,0 @@ -3,3,0 \ No newline at end of file diff --git a/src/python-example/rock_paper_scissors b/src/python-example/rock_paper_scissors deleted file mode 100644 index 2cf502ffd0..0000000000 --- a/src/python-example/rock_paper_scissors +++ /dev/null @@ -1,76 +0,0 @@ -''' - - Online Python Compiler. - Code, Compile, Run and Debug python program online. -Write your code in this editor and press "Run" button to execute it. - -''' -#module that allows us to select a random number -import random - -#dictionary -options = { {1, "rock"}, -{2, "paper"}, -{3, "scissors"} } - -#load previous users from file into list -#TO-DO -text_file = open("results.txt", "rw") -lines = text_file.read().split(',') -print lines -print len(lines) -text_file.close() - -#welcome message -print("Welcome to Rock, Paper, Scissors!") -name = ("Please enter your name.") - -#initialize user, computer choices -print("Please choose to continue...") -computer = random.randint(1,3) -choice = int( input("[1] Rock [2] Paper [3] Scissors [9] Quit Game\n") ) -print( choice ) - -#game will continue as long as user does not chose 9 -while not choice == 9: - #user entered invalid option - if not(( choice == 1 ) or ( choice == 2 ) or ( choice == 3 )): - print( "Invalid selection. Choose again.") - choice = input("[1] Rock [2] Paper [3] Scissors [9] Quit Game\n") - - #user chose ROCK - elif choice == 1: - if( computer == 1 ): - print( "Computer chose rock. Tie!" ) - elif( computer == 2 ): - print( "Computer chose paper. You lose :( ") - else: - print( "Computer chose scissors. You win :)" ) - - #user chose PAPER - elif choice == 2: - if( computer == 1 ): - print( "Computer chose rock. You win :)" ) - elif( computer == 2 ): - print( "Computer chose paper. Tie! ") - else: - print( "Computer chose scissors. You lose :(" ) - - #user chose SCISSORS - else: - if( computer == 1 ): - print( "Computer chose rock. You lose :(" ) - elif( computer == 2 ): - print( "Computer chose paper. You win :) ") - else: - print( "Computer chose scissors. Tie! " ) - print("\nPlease choose to continue...") - - #prompt user to make another selection - computer = random.randint(1, 3) - choice = input("[1] Rock [2] Paper [3] Scissors [9] Quit Game\n") - - -#implement ??? as a function -#TO-DO - diff --git a/src/python-example/rock_paper_scissors.py b/src/python-example/rock_paper_scissors.py deleted file mode 100644 index 4a1899f900..0000000000 --- a/src/python-example/rock_paper_scissors.py +++ /dev/null @@ -1,79 +0,0 @@ -#import module we need -import random - -#file i/o functions for historical results -def load_results(): - text_file = open("history.txt", "r") - history = text_file.read().split(",") - text_file.close() - return history - -def save_results( w, t, l): - text_file = open("history.txt", "w") - text_file.write( str(w) + "," + str(t) + "," + str(l)) - text_file.close() - -#welcome message -results = load_results() -wins = int(results[0]) -ties = int( results[1]) -losses = int(results[2]) -print("Welcome to Rock, Paper, Scissors!") -print("Wins: %s, Ties: %s, Losses: %s" % (wins, ties, losses)) -print("Please choose to continue...") - - -#initialize user, computer choices -computer = random.randint(1,3) -user = int(input("[1] Rock [2] Paper [3] Scissors [9] Quit\n")) - -#gamplay loop -while not user == 9: - #user chooses ROCK - if user == 1: - if computer == 1: - print("Computer chose rock...tie!") - ties += 1 - elif computer == 2: - print("Computer chose paper...computer wins :(") - losses += 1 - else: - print("Computer chose scissors...you wins :)") - wins += 1 - - #user chooses PAPER - elif user == 2: - if computer == 1: - print("Computer chose rock...you win :)") - wins += 1 - elif computer == 2: - print("Computer chose paper...tie!") - ties += 1 - else: - print("Computer chose scissors...computer wins :(") - losses += 1 - - #user chooses SCISSORS - elif user == 3: - if computer == 1: - print("Computer chose rock...computer wins :(") - losses += 1 - elif computer == 2: - print("Computer chose paper...you win :)") - wins += 1 - else: - print("Computer chose scissors...tie!") - ties += 1 - else: - print("Invalid selection. Please try again.") - #print updated stats - print("Wins: %s, Ties: %s, Losses: %s" % (wins, ties, losses)) - - #prompt user to make another selection - print("Please choose to continue...") - #initialize user, computer choices - computer = random.randint(1,3) - user = int(input("[1] Rock [2] Paper [3] Scissors [9] Quit\n")) - -# #game over, save results -save_results(wins, ties, losses) \ No newline at end of file From 43c7afa9928a9303a9a0c319888af037353448dd Mon Sep 17 00:00:00 2001 From: LisaCee Date: Tue, 26 Nov 2019 19:35:04 -0800 Subject: [PATCH 36/52] hello --- src/00_hello.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/00_hello.py b/src/00_hello.py index 268998dfc7..a397544874 100644 --- a/src/00_hello.py +++ b/src/00_hello.py @@ -1 +1,2 @@ -# Print "Hello, world!" to your terminal \ No newline at end of file +# Print "Hello, world!" to your terminal +print('Hello, world!') From e084b4ace8c6db7bbb8dd4aee4b4cc181253cc1f Mon Sep 17 00:00:00 2001 From: LisaCee Date: Tue, 26 Nov 2019 19:38:48 -0800 Subject: [PATCH 37/52] bignum --- src/01_bignum.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/01_bignum.py b/src/01_bignum.py index c020928d63..2b41cda051 100644 --- a/src/01_bignum.py +++ b/src/01_bignum.py @@ -1,4 +1,5 @@ # Print out 2 to the 65536 power # (try doing the same thing in the JS console and see what it outputs) -# YOUR CODE HERE \ No newline at end of file +# YOUR CODE HERE +print(pow(2, 65536)) From c7a83573e03d31f6d023514c5b5a204cff9a7531 Mon Sep 17 00:00:00 2001 From: LisaCee Date: Tue, 26 Nov 2019 19:43:53 -0800 Subject: [PATCH 38/52] data types --- src/02_datatypes.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/02_datatypes.py b/src/02_datatypes.py index 54178a241e..5a6c8ca465 100644 --- a/src/02_datatypes.py +++ b/src/02_datatypes.py @@ -14,8 +14,9 @@ # Write a print statement that combines x + y into the integer value 12 # YOUR CODE HERE - +print(x + int(y)) # Write a print statement that combines x + y into the string value 57 -# YOUR CODE HERE \ No newline at end of file +# YOUR CODE HERE +print(str(x) + y) From 5139d966d1624b045fcead2ecbe82108fe690eb9 Mon Sep 17 00:00:00 2001 From: LisaCee Date: Tue, 26 Nov 2019 19:48:46 -0800 Subject: [PATCH 39/52] modules --- src/03_modules.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/03_modules.py b/src/03_modules.py index 97eba053c7..747f29fb0e 100644 --- a/src/03_modules.py +++ b/src/03_modules.py @@ -5,27 +5,28 @@ level operating system functionality. """ +import os import sys # See docs for the sys module: https://docs.python.org/3.7/library/sys.html # Print out the command line arguments in sys.argv, one per line: # YOUR CODE HERE - +print(sys.argv) # Print out the OS platform you're using: # YOUR CODE HERE - +print(sys.platform) # Print out the version of Python you're using: # YOUR CODE HERE +print(sys.version) - -import os # See the docs for the OS module: https://docs.python.org/3.7/library/os.html # Print the current process ID # YOUR CODE HERE - +print(os.getpid()) # Print the current working directory (cwd): # YOUR CODE HERE - +print(os.getcwd()) # Print out your machine's login name # YOUR CODE HERE +print(os.getlogin()) From 9ee41487e251a9c64b2b46641a81b3643ec8c7f4 Mon Sep 17 00:00:00 2001 From: LisaCee Date: Tue, 26 Nov 2019 20:02:47 -0800 Subject: [PATCH 40/52] printing --- src/04_printing.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/04_printing.py b/src/04_printing.py index 06aaa7ff16..4208703833 100644 --- a/src/04_printing.py +++ b/src/04_printing.py @@ -11,7 +11,8 @@ # Using the printf operator (%), print the following feeding in the values of x, # y, and z: # x is 10, y is 2.25, z is "I like turtles!" - +print("x is %d, y is %.2f, z is \"%s\"" % (x, y, z)) # Use the 'format' string method to print the same thing - -# Finally, print the same thing using an f-string \ No newline at end of file +print("x is {}, y is {:.2f}, z is \"{}\"".format(x, y, z)) +# Finally, print the same thing using an f-string +print(f'x is {x}, y is {round(y, 2)}, z is "{z}"') From 54f106aa10fbf1b2814de89ab447e18d9a15020a Mon Sep 17 00:00:00 2001 From: LisaCee Date: Wed, 27 Nov 2019 12:57:52 -0800 Subject: [PATCH 41/52] started with lists --- src/05_lists.py | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/05_lists.py b/src/05_lists.py index 6b7d307182..baa3e60526 100644 --- a/src/05_lists.py +++ b/src/05_lists.py @@ -7,23 +7,24 @@ # For the following, DO NOT USE AN ASSIGNMENT (=). # Change x so that it is [1, 2, 3, 4] -# YOUR CODE HERE -print(x) +# YOUR CODE HERE +print(x.append(4)) # Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10] -# YOUR CODE HERE -print(x) +# YOUR CODE HERE +print(x.extend(y)) # Change x so that it is [1, 2, 3, 4, 9, 10] -# YOUR CODE HERE -print(x) +# YOUR CODE HERE + +print(x.extend(y)) # Change x so that it is [1, 2, 3, 4, 9, 99, 10] -# YOUR CODE HERE +# YOUR CODE HERE print(x) # Print the length of list x -# YOUR CODE HERE - +# YOUR CODE HERE +print(len(x)) # Print all the values in x multiplied by 1000 -# YOUR CODE HERE \ No newline at end of file +# YOUR CODE HERE From f5a03bf3902003943010a39fc8d7661733f43188 Mon Sep 17 00:00:00 2001 From: LisaCee Date: Thu, 28 Nov 2019 13:21:50 -0800 Subject: [PATCH 42/52] lists --- src/05_lists.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/05_lists.py b/src/05_lists.py index baa3e60526..8601b4dc93 100644 --- a/src/05_lists.py +++ b/src/05_lists.py @@ -8,19 +8,22 @@ # Change x so that it is [1, 2, 3, 4] # YOUR CODE HERE -print(x.append(4)) +x.append(4) +print(x) # Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10] # YOUR CODE HERE -print(x.extend(y)) +x.extend(y) +print(x) # Change x so that it is [1, 2, 3, 4, 9, 10] # YOUR CODE HERE - -print(x.extend(y)) +x.remove(8) +print(x) # Change x so that it is [1, 2, 3, 4, 9, 99, 10] # YOUR CODE HERE +x.insert(5, 99) print(x) # Print the length of list x @@ -28,3 +31,5 @@ print(len(x)) # Print all the values in x multiplied by 1000 # YOUR CODE HERE +for num in x: + print(num * 1000) From f1b8ddd3039e33dda124f1b15e154885cc079cb6 Mon Sep 17 00:00:00 2001 From: LisaCee Date: Thu, 28 Nov 2019 13:24:11 -0800 Subject: [PATCH 43/52] tuples --- src/06_tuples.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/06_tuples.py b/src/06_tuples.py index 016e540801..c3bf2ab809 100644 --- a/src/06_tuples.py +++ b/src/06_tuples.py @@ -3,27 +3,27 @@ are usually used to hold heterogenous data, as opposed to lists which are typically used to hold homogenous data. Tuples use parens instead of square brackets. - More specifically, tuples are faster than lists. If you're looking to just define a constant set of values and that set of values never needs to be mutated, use a tuple instead of a list. - Additionally, your code will be safer if you opt to "write-protect" data that does not need to be changed. Tuples enforce immutability automatically. """ -# Example: +# # Example: import math + def dist(a, b): """Compute the distance between two x,y points.""" x0, y0 = a # Destructuring assignment x1, y1 = b - + return math.sqrt((x1 - x0)**2 + (y1 - y0)**2) + a = (2, 7) # <-- x,y coordinates stored in tuples b = (-14, 72) @@ -31,14 +31,17 @@ def dist(a, b): print("Distance is: {:.2f}".format(dist(a, b))) - # Write a function `print_tuple` that prints all the values in a tuple # YOUR CODE HERE +def print_tuple(x): + for num in x: + print(num) + t = (1, 2, 5, 7, 99) print_tuple(t) # Prints 1 2 5 7 99, one per line # Declare a tuple of 1 element then print it -u = (1) # What needs to be added to make this work? +u = (1,) # What needs to be added to make this work? print_tuple(u) From badebe7c67c736f908f8163a22409bb68752f784 Mon Sep 17 00:00:00 2001 From: LisaCee Date: Thu, 28 Nov 2019 13:25:07 -0800 Subject: [PATCH 44/52] slices ^X --- src/07_slices.py | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/src/07_slices.py b/src/07_slices.py index 5e0b3bd8ee..7fe7b647c2 100644 --- a/src/07_slices.py +++ b/src/07_slices.py @@ -1,37 +1,35 @@ """ -Python exposes a terse and intuitive syntax for performing -slicing on lists and strings. This makes it easy to reference -only a portion of a list or string. - -This Stack Overflow answer provides a brief but thorough -overview: https://stackoverflow.com/a/509295 - -Use Python's slice syntax to achieve the following: +# Python exposes a terse and intuitive syntax for performing +# slicing on lists and strings. This makes it easy to reference +# only a portion of a list or string. +# This Stack Overflow answer provides a brief but thorough +# overview: https://stackoverflow.com/a/509295 +# Use Python's slice syntax to achieve the following: """ a = [2, 4, 1, 7, 9, 6] # Output the second element: 4: -print() +print(a[1]) # Output the second-to-last element: 9 -print() +print(a[-2]) # Output the last three elements in the array: [7, 9, 6] -print() +print(a[-3:]) # Output the two middle elements in the array: [1, 7] -print() +print(a[2:4]) # Output every element except the first one: [4, 1, 7, 9, 6] -print() +print(a[1:]) # Output every element except the last one: [2, 4, 1, 7, 9] -print() +print(a[:-1]) # For string s... s = "Hello, world!" # Output just the 8th-12th characters: "world" -print() \ No newline at end of file +print(s[-6:-1]) From 0314f69b5f4b2e8cb25d7379f46f456fe26aa8b1 Mon Sep 17 00:00:00 2001 From: LisaCee Date: Sun, 1 Dec 2019 10:37:02 -0800 Subject: [PATCH 45/52] list comp --- src/08_comprehensions.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/08_comprehensions.py b/src/08_comprehensions.py index 67eb742e50..e12c3fc52e 100644 --- a/src/08_comprehensions.py +++ b/src/08_comprehensions.py @@ -11,22 +11,26 @@ # Write a list comprehension to produce the array [1, 2, 3, 4, 5] y = [] - -print (y) +for x in range(1, 6): + y.append(x) +print(y) # Write a list comprehension to produce the cubes of the numbers 0-9: # [0, 1, 8, 27, 64, 125, 216, 343, 512, 729] y = [] - +for x in range(10): + y.append(x**3) print(y) # Write a list comprehension to produce the uppercase version of all the # elements in array a. Hint: "foo".upper() is "FOO". a = ["foo", "bar", "baz"] - y = [] +for x in a: + x = x.upper() + y.append(x) print(y) @@ -36,6 +40,6 @@ x = input("Enter comma-separated numbers: ").split(',') # What do you need between the square brackets to make it work? -y = [] +y = [i for i in x if int(i) % 2 == 0] -print(y) \ No newline at end of file +print(y) From b0110156e40ae220c8cef36e8e2388a1db5f1c49 Mon Sep 17 00:00:00 2001 From: LisaCee Date: Sun, 1 Dec 2019 10:49:52 -0800 Subject: [PATCH 46/52] dicts --- src/09_dictionaries.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/09_dictionaries.py b/src/09_dictionaries.py index 687a2ae2dc..a7e2475405 100644 --- a/src/09_dictionaries.py +++ b/src/09_dictionaries.py @@ -20,25 +20,29 @@ "lat": 43, "lon": -121, "name": "a place" - }, + }, { "lat": 41, "lon": -123, "name": "another place" - }, + }, { "lat": 43, "lon": -122, "name": "a third place" } ] - # Add a new waypoint to the list # YOUR CODE HERE +waypoints.append({"lat": 27, "lon": -12, "name": "my house"}) # Modify the dictionary with name "a place" such that its longitude # value is -130 and change its name to "not a real place" # YOUR CODE HERE +waypoints[0]["lon"] = -130 +waypoints[0]["name"] = "not a real place" # Write a loop that prints out all the field values for all the waypoints -# YOUR CODE HERE \ No newline at end of file +# YOUR CODE HERE +for i in waypoints: + print(i) From f972dad53d357e36f5163c48e899e8405276a134 Mon Sep 17 00:00:00 2001 From: LisaCee Date: Sun, 1 Dec 2019 15:22:21 -0800 Subject: [PATCH 47/52] functions --- src/10_functions.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/10_functions.py b/src/10_functions.py index 5830100c2c..b1f6ca344b 100644 --- a/src/10_functions.py +++ b/src/10_functions.py @@ -8,5 +8,13 @@ # Print out "Even!" if the number is even. Otherwise print "Odd" -# YOUR CODE HERE +def evenOrOdd(num): + if num % 2 == 0: + print("Even!") + else: + print("Odd") + + +# YOUR CODE HERE +evenOrOdd(num) From cd4e94c52a56e2b7aa4ed07632d6770ebab902f6 Mon Sep 17 00:00:00 2001 From: LisaCee Date: Sun, 1 Dec 2019 15:34:29 -0800 Subject: [PATCH 48/52] args --- src/11_args.py | 38 ++++++++++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/src/11_args.py b/src/11_args.py index b23783d530..e482ba2ccc 100644 --- a/src/11_args.py +++ b/src/11_args.py @@ -6,6 +6,11 @@ # YOUR CODE HERE + +def f1(x, y): + return x + y + + print(f1(1, 2)) # Write a function f2 that takes any number of integer arguments and prints the @@ -13,6 +18,14 @@ # YOUR CODE HERE + +def f2(*args): + total = 0 + for num in args: + total = total + num + return total + + print(f2(1)) # Should print 1 print(f2(1, 3)) # Should print 4 print(f2(1, 4, -12)) # Should print -7 @@ -21,6 +34,7 @@ a = [7, 6, 5, 4] # What thing do you have to add to make this work? +a = 22 print(f2(a)) # Should print 22 # Write a function f3 that accepts either one or two arguments. If one argument, @@ -29,6 +43,14 @@ # YOUR CODE HERE + +def f3(x, y=0): + if x == x + y: + return x + 1 + else: + return x + y + + print(f3(1, 2)) # Should print 3 print(f3(8)) # Should print 9 @@ -42,16 +64,20 @@ # Google "python keyword arguments". # YOUR CODE HERE +def f4(**kwargs): + for key, value in kwargs.items(): + print("key: {}, value: {}".format(key, value)) + # Should print # key: a, value: 12 # key: b, value: 30 f4(a=12, b=30) -# Should print -# key: city, value: Berkeley -# key: population, value: 121240 -# key: founded, value: "March 23, 1868" +# # Should print +# # key: city, value: Berkeley +# # key: population, value: 121240 +# # key: founded, value: "March 23, 1868" f4(city="Berkeley", population=121240, founded="March 23, 1868") d = { @@ -59,5 +85,5 @@ "hp": 3 } -# What thing do you have to add to make this work? -f4(d) \ No newline at end of file +# # What thing do you have to add to make this work? +f4(d=d) From 8235756e60bb75639b10efafa8a8a19b84e74271 Mon Sep 17 00:00:00 2001 From: LisaCee Date: Mon, 2 Dec 2019 09:25:39 -0800 Subject: [PATCH 49/52] scope --- src/12_scopes.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/12_scopes.py b/src/12_scopes.py index 339ae1915e..c3d0e54e00 100644 --- a/src/12_scopes.py +++ b/src/12_scopes.py @@ -4,9 +4,12 @@ # When you use a variable in a function, it's local in scope to the function. x = 12 + def changeX(): + global x x = 99 + changeX() # This prints 12. What do we have to modify in changeX() to get it to print 99? @@ -19,6 +22,7 @@ def outer(): y = 120 def inner(): + nonlocal y y = 999 inner() @@ -27,4 +31,5 @@ def inner(): # 999? Google "python nested function scope". print(y) -outer() \ No newline at end of file + +outer() From 6a728d2dbce7d48077a45572af1ec96ccb223e65 Mon Sep 17 00:00:00 2001 From: LisaCee Date: Mon, 2 Dec 2019 18:55:49 -0800 Subject: [PATCH 50/52] file io --- src/13_file_io.py | 10 +++++++++- src/bar.txt | 3 +++ 2 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 src/bar.txt diff --git a/src/13_file_io.py b/src/13_file_io.py index f0ddeb0020..b725cd74e2 100644 --- a/src/13_file_io.py +++ b/src/13_file_io.py @@ -9,10 +9,18 @@ # Print all the contents of the file, then close the file # YOUR CODE HERE +x = open('foo.txt', 'r') +for line in x: + print(line) +x.close() # Open up a file called "bar.txt" (which doesn't exist yet) for # writing. Write three lines of arbitrary content to that file, # then close the file. Open up "bar.txt" and inspect it to make # sure that it contains what you expect it to contain -# YOUR CODE HERE \ No newline at end of file +# YOUR CODE HERE +string = 'Hello\nHow are you?\nI am fine' +y = open('bar.txt', 'w') +y.write(string) +y.close() \ No newline at end of file diff --git a/src/bar.txt b/src/bar.txt new file mode 100644 index 0000000000..cfc792f806 --- /dev/null +++ b/src/bar.txt @@ -0,0 +1,3 @@ +Hello +How are you? +I am fine \ No newline at end of file From 37c7cc4144aff9b8264049220807fd9e2be78fa9 Mon Sep 17 00:00:00 2001 From: LisaCee Date: Mon, 2 Dec 2019 19:18:42 -0800 Subject: [PATCH 51/52] calendar --- src/14_cal.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/14_cal.py b/src/14_cal.py index 26010fa008..b8a689b519 100644 --- a/src/14_cal.py +++ b/src/14_cal.py @@ -21,4 +21,23 @@ import sys import calendar -from datetime import datetime \ No newline at end of file +from datetime import datetime + +lengthArg = len(sys.argv) + +cal = calendar.TextCalendar() + +if lengthArg == 2: + month = None + year = int(sys.argv[1]) +elif lengthArg == 3: + month = int(sys.argv[1]) + year = int(sys.argv[2]) +else: + print("usage: cal.py [month] year") + sys.exit(1) + +if month != None: + cal.prmonth(year, month) +else: + cal.pryear(year) \ No newline at end of file From a6838e7c7e5c22de337d7688bbc7c0e18b3de538 Mon Sep 17 00:00:00 2001 From: LisaCee Date: Mon, 2 Dec 2019 19:56:02 -0800 Subject: [PATCH 52/52] classes with some help --- src/15_classes.py | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/src/15_classes.py b/src/15_classes.py index e4425325cd..b77c3423d4 100644 --- a/src/15_classes.py +++ b/src/15_classes.py @@ -2,20 +2,34 @@ # constructor # YOUR CODE HERE - +class LatLon: + def __init__(self, lat, lon): + self.lat = lat + self.lon = lon # Make a class Waypoint that can be passed parameters `name`, `lat`, and `lon` to the # constructor. It should inherit from LatLon. Look up the `super` method. - +class Waypoint(LatLon): + def __init__(self, name, lat, lon): + super().__init__(lat, lon) + self.name = name + def __str__(self): + return 'Waypoint of %s: Lat %s and Lon %s' %(self.name, self.lat, self.lon) # YOUR CODE HERE # Make a class Geocache that can be passed parameters `name`, `difficulty`, # `size`, `lat`, and `lon` to the constructor. What should it inherit from? - # YOUR CODE HERE +class Geocache(Waypoint): + def __init__(self, name, difficulty, size, lat, lon): + super().__init__(name, lat, lon) + self.difficulty = difficulty + self.size = size + def __str__(self): + return f'Waypoint of {self.name}: Lat {self.lat}, Lon {self.lon}. Difficulty is {self.difficulty} and size is {self.size}' # Make a new waypoint and print it out: "Catacombs", 41.70505, -121.51521 - # YOUR CODE HERE +waypoint = Waypoint("Catacombs", 41.70505, -121.51521).__str__() # Without changing the following line, how can you make it print into something # more human-readable? Hint: Look up the `object.__str__` method @@ -24,6 +38,7 @@ # Make a new geocache "Newberry Views", diff 1.5, size 2, 44.052137, -121.41556 # YOUR CODE HERE +geocache = Geocache("Newberry Views", 1.5, 2, 44.052137, -121.41556).__str__() # Print it--also make this print more nicely -print(geocache) +print(geocache) \ No newline at end of file