From 0be5e4cadba60e668157a5863db7e91b0410e981 Mon Sep 17 00:00:00 2001 From: artbrgn <54554129+artbrgn@users.noreply.github.com> Date: Wed, 2 Sep 2020 22:47:01 -0500 Subject: [PATCH 1/3] update assignment --- src/00_hello.py | 5 +++- src/01_bignum.py | 3 +- src/02_datatypes.py | 8 +++--- src/03_modules.py | 30 +++++++++++++------- src/04_printing.py | 18 +++++++++--- src/05_lists.py | 24 +++++++++------- src/06_tuples.py | 19 +++++++------ src/07_slices.py | 15 ++++++---- src/08_comprehensions.py | 28 ++++++++++--------- src/09_dictionaries.py | 19 +++++++++---- src/10_functions.py | 15 ++++++---- src/11_args.py | 59 ++++++++++++++++++++++++++++++---------- src/12_scopes.py | 15 ++++++++-- src/13_file_io.py | 16 +++++++++-- 14 files changed, 186 insertions(+), 88 deletions(-) diff --git a/src/00_hello.py b/src/00_hello.py index 268998dfc7..71629f8b18 100644 --- a/src/00_hello.py +++ b/src/00_hello.py @@ -1 +1,4 @@ -# Print "Hello, world!" to your terminal \ No newline at end of file +# Print "Hello, world!" to your terminal +hi = 'Hello, world!' + +print(hi) diff --git a/src/01_bignum.py b/src/01_bignum.py index c020928d63..fc6f4f264e 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) +big = 2**65536 -# YOUR CODE HERE \ No newline at end of file +print(big) diff --git a/src/02_datatypes.py b/src/02_datatypes.py index 245193da34..83907e6991 100644 --- a/src/02_datatypes.py +++ b/src/02_datatypes.py @@ -2,7 +2,6 @@ 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. @@ -12,10 +11,11 @@ y = "7" # Write a print statement that combines x + y into the integer value 12 - -# YOUR CODE HERE +in = x + int(y) # Write a print statement that combines x + y into the string value 57 +st = str(x) + y -# YOUR CODE HERE \ No newline at end of file +print(in) +print(st) diff --git a/src/03_modules.py b/src/03_modules.py index 97eba053c7..650ec6994e 100644 --- a/src/03_modules.py +++ b/src/03_modules.py @@ -5,27 +5,37 @@ 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 +arguements = [arg for arg in sys.argv] +for i, arg in enumerate(arguements): + print(f'Arguments{i}: {arg}') +print() # Print out the OS platform you're using: -# YOUR CODE HERE +OS_platform = sys.platform +print(f'Operating System: {OS_platform}') +print() # Print out the version of Python you're using: -# YOUR CODE HERE - +python_version = sys.version +print(f'Python Version: {python_version}') +print() -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 +process_ID = os.getpid() +print(f'Current Process ID: {process_ID}') +print() # Print the current working directory (cwd): -# YOUR CODE HERE +current_dir = os.getcwd() +print(f'CWD: {current_dir}') +print() # Print out your machine's login name -# YOUR CODE HERE +name = os.getlogin() +print(f'Login Name: {name}') +print() diff --git a/src/04_printing.py b/src/04_printing.py index 06aaa7ff16..1a1df6c248 100644 --- a/src/04_printing.py +++ b/src/04_printing.py @@ -1,17 +1,27 @@ """ Python provides a number of ways to perform printing. Research -how to print using the printf operator, the `format` string +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!" -# Using the printf operator (%), print the following feeding in the values of x, +# 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!" +format_1 = 'x is %d, y is %2.2f, z is "%s"' % (x, y, z) +print(format_1) +print() # Use the 'format' string method to print the same thing +format_2 = 'x is {}'.format(x) ++ ', y is {:.2f}'.format(y) + ', z is "{}"'.format(z) +print(format_2) +print() -# Finally, print the same thing using an f-string \ No newline at end of file +# Finally, print the same thing using an f-string +format_3 = f'x is {x}, y is {y:.{2}f}, z is "{z}"' +print(format_3) +print() diff --git a/src/05_lists.py b/src/05_lists.py index cfccc4e945..7db0cec2ed 100644 --- a/src/05_lists.py +++ b/src/05_lists.py @@ -1,4 +1,5 @@ -# For the exercise, look up the methods and functions that are available for use +# For the exercise, look up the methods and +# functions that are available for use # with Python lists. x = [1, 2, 3] @@ -7,23 +8,26 @@ # For the following, DO NOT USE AN ASSIGNMENT (=). # Change x so that it is [1, 2, 3, 4] -# YOUR CODE HERE -print(x) +x.append(4) # Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10] -# YOUR CODE HERE -print(x) +x.extend([n for n in y]) # Change x so that it is [1, 2, 3, 4, 9, 10] -# YOUR CODE HERE -print(x) +x.remove(8) # Change x so that it is [1, 2, 3, 4, 9, 99, 10] -# YOUR CODE HERE +x.insert(-1, 99) print(x) +print() # Print the length of list x -# YOUR CODE HERE +length = len(x) +print(length) +print() # Print all the values in x multiplied by 1000 -# YOUR CODE HERE \ No newline at end of file +# YOUR CODE HERE +list_comp = [n * 1000 for n in x] +print(list_comp) +print() diff --git a/src/06_tuples.py b/src/06_tuples.py index 36754da73b..a1ee3dad00 100644 --- a/src/06_tuples.py +++ b/src/06_tuples.py @@ -3,11 +3,9 @@ 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. @@ -17,6 +15,7 @@ import math + def dist(a, b): """Compute the distance between two x,y points.""" x0, y0 = a # Destructuring assignment @@ -26,19 +25,21 @@ def dist(a, b): 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))) - - +print() # Write a function `print_tuple` that prints all the values in a tuple -# YOUR CODE HERE + +def print_tuple(tup): + for i in tup: + print(i) t = (1, 2, 5, 7, 99) -print_tuple(t) # Prints 1 2 5 7 99, one per line +print_tuple(t) +print() # 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) +print() diff --git a/src/07_slices.py b/src/07_slices.py index 5e0b3bd8ee..e5bd1d6e75 100644 --- a/src/07_slices.py +++ b/src/07_slices.py @@ -1,32 +1,36 @@ """ -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 - 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[3:]) print() # Output the two middle elements in the array: [1, 7] +print(a[2:-2]) 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[:-1]) print() # For string s... @@ -34,4 +38,5 @@ s = "Hello, world!" # Output just the 8th-12th characters: "world" -print() \ No newline at end of file +print(s[7:12]) +print() diff --git a/src/08_comprehensions.py b/src/08_comprehensions.py index 67eb742e50..6d59e5ca0e 100644 --- a/src/08_comprehensions.py +++ b/src/08_comprehensions.py @@ -2,33 +2,34 @@ 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. +the list should be populated. -Take a look at https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions +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) +ar = [n for n in range(1, 6)] +print(ar) +print() # 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) +cube= [n ** 3 for n in range(10)] +print(cube) +print() # 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) +up = [s.upper() for s in a] +print(up) +print() # Use a list comprehension to create a list containing only the _even_ elements # the user entered into list x. @@ -36,6 +37,7 @@ 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 +ev = [int(n) for n in x if int(n) % 2 == 0] +print(ev) +print() diff --git a/src/09_dictionaries.py b/src/09_dictionaries.py index a8b2911f64..0036a3cf49 100644 --- a/src/09_dictionaries.py +++ b/src/09_dictionaries.py @@ -4,10 +4,8 @@ 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 @@ -34,14 +32,25 @@ ] # Add a new waypoint to the list -# YOUR CODE HERE +waypoints.append( + { + "lat": 37, + "lon": 122, + "name": "GGB" + } +) # Modify the dictionary with name "a place" such that its longitude # value is -130 and change its name to "not a real place" # Note: It's okay to access the dictionary using bracket notation on the # waypoints list. -# 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 + +for dic in waypoints: + for key, value in zip(dic.keys(), dic.values()): + print(f'{key}: {value}') + print() diff --git a/src/10_functions.py b/src/10_functions.py index 5830100c2c..1911011c19 100644 --- a/src/10_functions.py +++ b/src/10_functions.py @@ -1,12 +1,17 @@ -# Write a function is_even that will return true if the passed-in number is even. +# Write a function is_even that will return +# true if the passed-in number is even. -# 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) # 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 8c467ea47f..48d3b04ede 100644 --- a/src/11_args.py +++ b/src/11_args.py @@ -4,36 +4,58 @@ # 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 +def f1(a, b): + return a + b print(f1(1, 2)) +print() -# Write a function f2 that takes any number of integer arguments and returns the +# Write a function f2 that takes any number +# of integer arguments and returns the # sum. # Note: 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 +def f2(*argv): + a = 0 + for n in argv: + a += n + return a + a = [7, 6, 5, 4] +print(f2(1)) +print() +print(f2(1, 3)) +print() +print(f2(1, 4, -12)) +print() +print(f2(7, 9, 1, 3, 4, 9, 0)) +print() +print(f2(*a)) +print() # How do you have to modify the f2 call below to make this work? -print(f2(a)) # Should print 22 -# Write a function f3 that accepts either one or two arguments. If one argument, +# 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. # Note: Google "python default arguments" for a hint. -# YOUR CODE HERE - -print(f3(1, 2)) # Should print 3 -print(f3(8)) # Should print 9 +def f3(*argv): + a = 0 + for i in argv: + a += i + if a == argv[0]: + return argv[0] + 1 + else: + return a +print(f3(1, 2)) +print() +print(f3(8)) +print() # Write a function f4 that accepts an arbitrary number of keyword arguments and # prints out the keys and values like so: @@ -43,18 +65,24 @@ # # Note: Google "python keyword arguments". -# YOUR CODE HERE + +def f4(**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) +print() # 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") +print() d = { "monster": "goblin", @@ -62,4 +90,5 @@ } # How do you have to modify the f4 call below to make this work? -f4(d) +f4(**d) +print() diff --git a/src/12_scopes.py b/src/12_scopes.py index bc467fa423..742a36515c 100644 --- a/src/12_scopes.py +++ b/src/12_scopes.py @@ -1,16 +1,20 @@ # Experiment with scopes in Python. -# Good reading: https://www.programiz.com/python-programming/global-local-nonlocal-variables +# 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 change_x(): + global x x = 99 change_x() -# This prints 12. What do we have to modify in change_x() to get it to print 99? -print(x) +# This prints 12. What do we have to modify in +# change_x() to get it to print 99? +# print(x) # This nested function has a similar problem. @@ -19,6 +23,7 @@ def outer(): y = 120 def inner(): + nonlocal y y = 999 inner() @@ -29,4 +34,8 @@ def inner(): print(y) +# outer() +print(x) +print('----------') outer() +print('----------') diff --git a/src/13_file_io.py b/src/13_file_io.py index 3c68f8aba2..37d85a1acd 100644 --- a/src/13_file_io.py +++ b/src/13_file_io.py @@ -1,19 +1,29 @@ """ 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 -# Note: pay close attention to your current directory when trying to open "foo.txt" +# Note: pay close attention to your current +# directory when trying to open "foo.txt" # YOUR CODE HERE +with open('foo.txt') as f: + foo = f.read() # 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('bar.txt') as f: + bar = f.read() + # print(bar) + +print(foo) +print('--------------------') +print(bar) +print('--------------------') From 68a9e64540cd255d1adbada5b0b7ffb2e8d4c64e Mon Sep 17 00:00:00 2001 From: artbrgn <54554129+artbrgn@users.noreply.github.com> Date: Thu, 3 Sep 2020 20:23:57 -0500 Subject: [PATCH 2/3] switched branches --- src/12_scopes.py | 8 +++----- src/13_file_io.py | 8 ++------ 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/src/12_scopes.py b/src/12_scopes.py index 742a36515c..9fcf90f5fe 100644 --- a/src/12_scopes.py +++ b/src/12_scopes.py @@ -14,7 +14,8 @@ def change_x(): # This prints 12. What do we have to modify in # change_x() to get it to print 99? -# print(x) +print(x) +print() # This nested function has a similar problem. @@ -34,8 +35,5 @@ def inner(): print(y) -# outer() -print(x) -print('----------') + outer() -print('----------') diff --git a/src/13_file_io.py b/src/13_file_io.py index 37d85a1acd..2254d1dbc1 100644 --- a/src/13_file_io.py +++ b/src/13_file_io.py @@ -9,21 +9,17 @@ # Note: pay close attention to your current # directory when trying to open "foo.txt" -# YOUR CODE HERE with open('foo.txt') as f: foo = f.read() +print(foo) +print() # 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 with open('bar.txt') as f: bar = f.read() # print(bar) - -print(foo) -print('--------------------') print(bar) -print('--------------------') From cad9563113ca0ba062b4f23cc8cb82d1b1378976 Mon Sep 17 00:00:00 2001 From: artbrgn <54554129+artbrgn@users.noreply.github.com> Date: Sun, 6 Sep 2020 14:13:54 -0500 Subject: [PATCH 3/3] Updating second half --- src/14_cal.py | 28 +++++++++++++++++++++++----- src/15_classes.py | 45 ++++++++++++++++++++++++++++++++++++++------- src/foo.txt | 2 +- 3 files changed, 62 insertions(+), 13 deletions(-) diff --git a/src/14_cal.py b/src/14_cal.py index 30bb10d113..44fb8f47a2 100644 --- a/src/14_cal.py +++ b/src/14_cal.py @@ -18,15 +18,33 @@ the format that your program expects arguments to be given. Then exit the program. -Note: the user should provide argument input (in the initial call to run the file) and not -prompted input. Also, the brackets around year are to denote that the argument is +Note: the user should provide argument input (in the initial +call to run the file) and not +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 -print out a calendar for April in 2015, but if you omit either the year or both values, +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 + +today = datetime.today() +yy, mm = today.year, today.month + +if len(sys.argv) == 1: + print(calendar.month(yy, mm)) +elif len(sys.argv) == 2: + yy, mm = yy, int(sys.argv[1]) + print(calendar.month(yy, mm)) +elif len(sys.argv) == 3: + yy, mm = int(sys.argv[2]), int(sys.argv[1]) + print(calendar.month(yy, mm)) +else: + print('Please give command in format "python3 14_cal.py [month] [year]"') diff --git a/src/15_classes.py b/src/15_classes.py index 2355dd20b7..8ab03e81c9 100644 --- a/src/15_classes.py +++ b/src/15_classes.py @@ -1,29 +1,60 @@ # 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 +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? -# YOUR CODE HERE + +class Geocache(waypoint): + def __init__(self, lat, lon, name, difficulty, size): + super().__init__(name, lat, lon) + self.difficulty = difficulty + self.size = size + + def __str__(self): + return "{self.name}, {self.difficulty}, {self.size}, {self.lat}, {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) +print(waypoint) + # Without changing the following line, how can you make it print into something # more human-readable? Hint: Look up the `object.__str__` method +class waypoint(LatLon): + def __init__(self, name, lat, lon): + super().__init__(lat, lon) + self.name = name + + def __str__(self): + return "{self.name}, {self.lat}, {self.lon}".format(self=self) + +waypoint = waypoint("Catacombs", 41.70505, -121.51521) print(waypoint) # Make a new geocache "Newberry Views", diff 1.5, size 2, 44.052137, -121.41556 -# YOUR CODE HERE +geo = Geocache(44.052137, -121.41556, name="Newberry Views", + difficulty='diff 1.5', size='size 2') # Print it--also make this print more nicely -print(geocache) +# print(geocache) +print(geo) diff --git a/src/foo.txt b/src/foo.txt index 9793c085e1..ca9fd246c9 100644 --- a/src/foo.txt +++ b/src/foo.txt @@ -3,4 +3,4 @@ I do bite my thumb, sir. Do you bite your thumb at us, sir? No, sir. I do not bite my thumb at you, sir, but I bite my thumb, sir. Do you quarrel, sir? -Quarrel, sir? No, sir. \ No newline at end of file +Quarrel, sir? No, sir.