diff --git a/src/00_hello.py b/src/00_hello.py index 268998dfc7..8913f3d0f8 100644 --- a/src/00_hello.py +++ b/src/00_hello.py @@ -1 +1,3 @@ -# Print "Hello, world!" to your terminal \ No newline at end of file +# Print "Hello, world!" to your terminal + +print("Hello, world!") diff --git a/src/01_bignum.py b/src/01_bignum.py index c020928d63..a3f6f18716 100644 --- a/src/01_bignum.py +++ b/src/01_bignum.py @@ -1,4 +1,6 @@ # 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(2**65536) diff --git a/src/02_datatypes.py b/src/02_datatypes.py index 245193da34..216316f64a 100644 --- a/src/02_datatypes.py +++ b/src/02_datatypes.py @@ -14,8 +14,10 @@ # 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) diff --git a/src/03_modules.py b/src/03_modules.py index 97eba053c7..9d54e39e7e 100644 --- a/src/03_modules.py +++ b/src/03_modules.py @@ -5,27 +5,36 @@ 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 +for a in sys.argv: + print(a) # 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()) diff --git a/src/04_printing.py b/src/04_printing.py index 06aaa7ff16..fd08d545bd 100644 --- a/src/04_printing.py +++ b/src/04_printing.py @@ -11,7 +11,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('x is %d, y is %.2f and z is "%s"' % (x, y, z)) # Use the 'format' string method to print the same thing +print('x is {:d}, y is {:.2f} and z is "{:s}"'.format(x, y, z)) -# Finally, print the same thing using an f-string \ No newline at end of file +# Finally, print the same thing using an f-string +print(f'x is {x}, y is {y:.2f} and z is "{z}"') diff --git a/src/05_lists.py b/src/05_lists.py index cfccc4e945..5a05ff7d37 100644 --- a/src/05_lists.py +++ b/src/05_lists.py @@ -8,22 +8,30 @@ # Change x so that it is [1, 2, 3, 4] # YOUR CODE HERE +x.append(4) print(x) # Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10] # YOUR CODE HERE +for n in y: + x.append(n) print(x) # Change x so that it is [1, 2, 3, 4, 9, 10] # YOUR CODE HERE +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 # 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 +for a in x: + print(a*1000) diff --git a/src/06_tuples.py b/src/06_tuples.py index 36754da73b..53ef629aa3 100644 --- a/src/06_tuples.py +++ b/src/06_tuples.py @@ -17,6 +17,7 @@ import math + def dist(a, b): """Compute the distance between two x,y points.""" x0, y0 = a # Destructuring assignment @@ -24,6 +25,7 @@ def dist(a, b): return math.sqrt((x1 - x0)**2 + (y1 - y0)**2) + a = (2, 7) # <-- x,y coordinates stored in tuples b = (-14, 72) @@ -31,14 +33,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(v): + for n in v: + print(n) + 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) diff --git a/src/07_slices.py b/src/07_slices.py index 5e0b3bd8ee..14dd6a4056 100644 --- a/src/07_slices.py +++ b/src/07_slices.py @@ -1,7 +1,7 @@ """ -Python exposes a terse and intuitive syntax for performing +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. +only a portion of a list or string. This Stack Overflow answer provides a brief but thorough overview: https://stackoverflow.com/a/509295 @@ -12,26 +12,27 @@ 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() +l = int(len(a)/2) +print(a[l-1:l+1]) # Output every element except the first one: [4, 1, 7, 9, 6] -print() +print(a[1:len(a)]) # 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[7:12]) diff --git a/src/08_comprehensions.py b/src/08_comprehensions.py index 67eb742e50..1736b96eb2 100644 --- a/src/08_comprehensions.py +++ b/src/08_comprehensions.py @@ -11,14 +11,16 @@ # 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 @@ -27,7 +29,8 @@ a = ["foo", "bar", "baz"] y = [] - +for w in a: + y.append(w.upper()) print(y) # Use a list comprehension to create a list containing only the _even_ elements @@ -37,5 +40,7 @@ # What do you need between the square brackets to make it work? y = [] - -print(y) \ No newline at end of file +for n in x: + if int(n) % 2 == 0: + y.append(int(n)) +print(y) diff --git a/src/09_dictionaries.py b/src/09_dictionaries.py index a8b2911f64..72108f454f 100644 --- a/src/09_dictionaries.py +++ b/src/09_dictionaries.py @@ -35,6 +35,11 @@ # Add a new waypoint to the list # YOUR CODE HERE +waypoints.append({ + "lat": 55, + "lon": -120, + "name": "some random place" +}) # Modify the dictionary with name "a place" such that its longitude # value is -130 and change its name to "not a real place" @@ -42,6 +47,11 @@ # waypoints list. # YOUR CODE HERE +waypoints[0]['name'] = 'not a real place' +waypoints[0]['lon'] = -130 # 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 w in waypoints: + for v in w.values(): + print(v) diff --git a/src/10_functions.py b/src/10_functions.py index 5830100c2c..eb8798f662 100644 --- a/src/10_functions.py +++ b/src/10_functions.py @@ -2,6 +2,12 @@ # YOUR CODE HERE + +def is_even(n): + if n % 2 == 0: + return True + + # Read a number from the keyboard num = input("Enter a number: ") num = int(num) @@ -9,4 +15,7 @@ # Print out "Even!" if the number is even. Otherwise print "Odd" # YOUR CODE HERE - +if is_even(num): + print("Even!") +else: + print("Odd!") diff --git a/src/11_args.py b/src/11_args.py index 39a694ec94..18b8f20c08 100644 --- a/src/11_args.py +++ b/src/11_args.py @@ -5,7 +5,8 @@ # the sum. This is what you'd consider to be a regular, normal function. # 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,7 +14,14 @@ # Note: Google for "python arbitrary arguments" and look for "*args" # YOUR CODE HERE - +def f2(*nums): + l = len(nums) + if l == 0: + return 'No numbers were provided.' + elif l == 1: + return nums[0] + else: + return sum(nums) print(f2(1)) # Should print 1 print(f2(1, 3)) # Should print 4 print(f2(1, 4, -12)) # Should print -7 @@ -22,7 +30,7 @@ a = [7, 6, 5, 4] # How do you have to modify the f2 call below to make this work? -print(f2(a)) # Should print 22 +print(f2(a[0], a[1], a[2], a[3])) # 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 @@ -30,7 +38,8 @@ # Note: Google "python default arguments" for a hint. # YOUR CODE HERE - +def f3(m, n=1): + return m + n print(f3(1, 2)) # Should print 3 print(f3(8)) # Should print 9 @@ -44,6 +53,9 @@ # Note: Google "python keyword arguments". # YOUR CODE HERE +def f4(**kwargs): + for k, v in kwargs.items(): + print(f"{k} = {v}") # Should print # key: a, value: 12 @@ -62,4 +74,4 @@ } # How do you have to modify the f4 call below to make this work? -f4(d) +f4(monster=d["monster"], hp=d["hp"]) diff --git a/src/12_scopes.py b/src/12_scopes.py index bc467fa423..362525d5ce 100644 --- a/src/12_scopes.py +++ b/src/12_scopes.py @@ -5,6 +5,7 @@ x = 12 def change_x(): + global x x = 99 change_x() @@ -19,7 +20,8 @@ def outer(): y = 120 def inner(): - y = 999 + nonlocal y + y = 999 inner() diff --git a/src/13_file_io.py b/src/13_file_io.py index 3c68f8aba2..5682b5433a 100644 --- a/src/13_file_io.py +++ b/src/13_file_io.py @@ -11,9 +11,20 @@ # YOUR CODE HERE +# import os +# print(os.getcwd()) +with open('src\\foo.txt') as f: + file_data = f.read() + print(file_data) + + # 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 +with open('src\\bar.txt', 'w+') as g: + for i in range(3): + g.write("This is line %d\r\n" % (i+1)) + diff --git a/src/14_cal.py b/src/14_cal.py index 30bb10d113..b37218cec1 100644 --- a/src/14_cal.py +++ b/src/14_cal.py @@ -22,11 +22,31 @@ prompted input. Also, the brackets around year are to denote that the argument is optional, as this is a common convention in documentation. -This would mean that from the command line you would call `python3 14_cal.py 4 2015` to +This would mean that from the command line you would call `python3 14_cal.py 4 2015` to print out a calendar for April in 2015, but if you omit either the year or both values, it should use today’s date to get the month and year. """ import sys import calendar -from datetime import datetime \ No newline at end of file +from datetime import datetime + +l = len(sys.argv) +m = 0 +y = 0 +currentMonth = datetime.now().month +currentYear = datetime.now().year + +if l == 1: + m = currentMonth + y = currentYear +elif l == 2: + m = int(sys.argv[1]) + y = currentYear +elif l == 3: + m = int(sys.argv[1]) + y = int(sys.argv[2]) +else: + print('Please provide the necessary arguments') + +print(calendar.month(y,m)) diff --git a/src/15_classes.py b/src/15_classes.py index 2355dd20b7..7125f2653e 100644 --- a/src/15_classes.py +++ b/src/15_classes.py @@ -3,19 +3,40 @@ # 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. # YOUR CODE HERE +class Waypoint(Latlon): + def __init__(self, name, lat, lon): + super().__init__(lat, lon) + self.name = name -# Make a class Geocache that can be passed parameters `name`, `difficulty`, -# `size`, `lat`, and `lon` to the constructor. What should it inherit from? + def __str__(self): + return 'Name: {self.name}\nLatitude: {self.lat}\nLongitude: {self.lon}'.format(self=self) -# YOUR CODE HERE -# Make a new waypoint and print it out: "Catacombs", 41.70505, -121.51521 +# 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 'Name: {self.name}\nDifficulty: {self.difficulty}\nSize: {self.size}\nLatitude: {self.lat}\nLongitude: {self.lon}'.format(self=self) + # Make a new waypoint and print it out: "Catacombs", 41.70505, -121.51521 + # YOUR CODE HERE +waypoint = Waypoint("Catacombs", 41.70505, -121.51521) # 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 +45,6 @@ # 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) # Print it--also make this print more nicely print(geocache) diff --git a/src/bar.txt b/src/bar.txt new file mode 100644 index 0000000000..5c8cb4c8a4 --- /dev/null +++ b/src/bar.txt @@ -0,0 +1,3 @@ +This is line 1 +This is line 2 +This is line 3