diff --git a/documenting-python-code/README.md b/documenting-python-code/README.md index 6a25540df6..eb40bfef14 100644 --- a/documenting-python-code/README.md +++ b/documenting-python-code/README.md @@ -40,7 +40,7 @@ say_hello(name) A dog says woof ``` -Print the column headers of an Excel spreadsheet: +Print the column headers of a CSV or Excel spreadsheet: ```sh $ python spreadsheet_columns.py people.xlsx diff --git a/documenting-python-code/animal.py b/documenting-python-code/animal.py index 2d2ac999e7..d02ee69ae3 100644 --- a/documenting-python-code/animal.py +++ b/documenting-python-code/animal.py @@ -32,7 +32,7 @@ def __init__(self, name, sound, num_legs=4): sound : str The sound the animal makes num_legs : int, optional - The number of legs the animal (default is 4) + The number of legs the animal has (default is 4) """ self.name = name diff --git a/documenting-python-code/docstring_formats.py b/documenting-python-code/docstring_formats.py index 2960ed9364..e2016f4071 100644 --- a/documenting-python-code/docstring_formats.py +++ b/documenting-python-code/docstring_formats.py @@ -19,7 +19,10 @@ def get_spreadsheet_cols_google(file_loc, print_cols=False): list: a list of strings representing the header columns """ - file_data = pd.read_excel(file_loc) + if file_loc.lower().endswith(".csv"): + file_data = pd.read_csv(file_loc) + else: + file_data = pd.read_excel(file_loc) col_headers = list(file_data.columns.values) if print_cols: @@ -40,7 +43,10 @@ def get_spreadsheet_cols_rest(file_loc, print_cols=False): :rtype: list """ - file_data = pd.read_excel(file_loc) + if file_loc.lower().endswith(".csv"): + file_data = pd.read_csv(file_loc) + else: + file_data = pd.read_excel(file_loc) col_headers = list(file_data.columns.values) if print_cols: @@ -65,7 +71,10 @@ def get_spreadsheet_cols_numpy(file_loc, print_cols=False): a list of strings representing the header columns """ - file_data = pd.read_excel(file_loc) + if file_loc.lower().endswith(".csv"): + file_data = pd.read_csv(file_loc) + else: + file_data = pd.read_excel(file_loc) col_headers = list(file_data.columns.values) if print_cols: @@ -86,7 +95,10 @@ def get_spreadsheet_cols_epytext(file_loc, print_cols=False): @returns: a list of strings representing the header columns """ - file_data = pd.read_excel(file_loc) + if file_loc.lower().endswith(".csv"): + file_data = pd.read_csv(file_loc) + else: + file_data = pd.read_excel(file_loc) col_headers = list(file_data.columns.values) if print_cols: diff --git a/documenting-python-code/spreadsheet_columns.py b/documenting-python-code/spreadsheet_columns.py index 9abeb55137..b545594ba0 100644 --- a/documenting-python-code/spreadsheet_columns.py +++ b/documenting-python-code/spreadsheet_columns.py @@ -8,7 +8,8 @@ (.xls, .xlsx) files. This script requires that `pandas` be installed within the Python -environment you are running this script in. +environment you are running this script in, along with `openpyxl` for +.xlsx files and `xlrd` for .xls files. This file can also be imported as a module and contains the following functions: @@ -36,10 +37,13 @@ def get_spreadsheet_cols(file_loc, print_cols=False): Returns ------- list - a list of strings used that are the header columns + a list of strings that are the header columns """ - file_data = pd.read_excel(file_loc) + if file_loc.lower().endswith(".csv"): + file_data = pd.read_csv(file_loc) + else: + file_data = pd.read_excel(file_loc) col_headers = list(file_data.columns.values) if print_cols: @@ -49,7 +53,10 @@ def get_spreadsheet_cols(file_loc, print_cols=False): def main(): - parser = argparse.ArgumentParser(description=__doc__) + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, + ) parser.add_argument( "input_file", type=str, diff --git a/operator-function-overloading/custom_complex.py b/operator-function-overloading/custom_complex.py index a0cd7c184b..aca1ffe8bd 100644 --- a/operator-function-overloading/custom_complex.py +++ b/operator-function-overloading/custom_complex.py @@ -1,12 +1,12 @@ -from math import hypot, atan, sin, cos +from math import hypot, atan2, sin, cos class CustomComplex: """ A class to represent a complex number, a+bj. Attributes: - real - int, representing the real part - imag - int, representing the imaginary part + real - int or float, representing the real part + imag - int or float, representing the imaginary part Implements the following: @@ -41,17 +41,17 @@ def conjugate(self): Return: CustomComplex instance """ - return CustomComplex(self.real, -self.imag) + return self.__class__(self.real, -self.imag) def argz(self): """ Returns the argument of a complex number The argument is given by: - atan(imag_part/real_part) + atan2(imag_part, real_part) Return: float """ - return atan(self.imag / self.real) + return atan2(self.imag, self.real) def __abs__(self): """ @@ -69,7 +69,7 @@ def __repr__(self): Return: str """ - return f"CustomComplex({self.real}, {self.imag})" + return f"{self.__class__.__name__}({self.real}, {self.imag})" def __str__(self): """ @@ -87,15 +87,16 @@ def __add__(self, other): Return: CustomComplex instance """ - if isinstance(other, float) or isinstance(other, int): + if isinstance(other, (int, float)): real_part = self.real + other imag_part = self.imag - - if isinstance(other, CustomComplex): + elif isinstance(other, CustomComplex): real_part = self.real + other.real imag_part = self.imag + other.imag + else: + return NotImplemented - return CustomComplex(real_part, imag_part) + return self.__class__(real_part, imag_part) def __sub__(self, other): """ @@ -104,15 +105,16 @@ def __sub__(self, other): Return: CustomComplex instance """ - if isinstance(other, float) or isinstance(other, int): + if isinstance(other, (int, float)): real_part = self.real - other imag_part = self.imag - - if isinstance(other, CustomComplex): + elif isinstance(other, CustomComplex): real_part = self.real - other.real imag_part = self.imag - other.imag + else: + return NotImplemented - return CustomComplex(real_part, imag_part) + return self.__class__(real_part, imag_part) def __mul__(self, other): """ @@ -121,26 +123,27 @@ def __mul__(self, other): Return: CustomComplex instance """ - if isinstance(other, int) or isinstance(other, float): + if isinstance(other, (int, float)): real_part = self.real * other imag_part = self.imag * other - - if isinstance(other, CustomComplex): + elif isinstance(other, CustomComplex): real_part = (self.real * other.real) - (self.imag * other.imag) imag_part = (self.real * other.imag) + (self.imag * other.real) + else: + return NotImplemented - return CustomComplex(real_part, imag_part) + return self.__class__(real_part, imag_part) def __radd__(self, other): """ - Same as __add__; allows 1 + CustomComplex('x+yj') + Same as __add__; allows 1 + CustomComplex(x, y) x + y == y + x """ return self.__add__(other) def __rmul__(self, other): """ - Same as __mul__; allows 2 * CustomComplex('x+yj') + Same as __mul__; allows 2 * CustomComplex(x, y) x * y == y * x """ return self.__mul__(other) @@ -156,11 +159,13 @@ def __rsub__(self, other): Return: CustomComplex instance """ - if isinstance(other, float) or isinstance(other, int): + if isinstance(other, (int, float)): real_part = other - self.real imag_part = -self.imag + else: + return NotImplemented - return CustomComplex(real_part, imag_part) + return self.__class__(real_part, imag_part) def __eq__(self, other): """ @@ -171,6 +176,8 @@ def __eq__(self, other): Return: bool """ + if not isinstance(other, (int, float, CustomComplex)): + return NotImplemented # Note: comparing floats directly is not a good idea in general # due to floating-point precision return (self.real == other.real) and (self.imag == other.imag) @@ -184,6 +191,8 @@ def __ne__(self, other): Return: bool """ + if not isinstance(other, (int, float, CustomComplex)): + return NotImplemented return (self.real != other.real) or (self.imag != other.imag) def __pow__(self, other): @@ -204,4 +213,4 @@ def __pow__(self, other): real_part = round(r_raised * cos(argz_multiplied)) imag_part = round(r_raised * sin(argz_multiplied)) - return CustomComplex(real_part, imag_part) + return self.__class__(real_part, imag_part) diff --git a/python-data-classes/position_make_dataclass.py b/python-data-classes/position_make_dataclass.py index 5be429b501..a65f0e4164 100644 --- a/python-data-classes/position_make_dataclass.py +++ b/python-data-classes/position_make_dataclass.py @@ -1,3 +1,3 @@ from dataclasses import make_dataclass -Position = make_dataclass("Position", ["name", "lat", "lon"]) +Position = make_dataclass("Position", ["name", "lon", "lat"]) diff --git a/python-sql-libraries/README.md b/python-sql-libraries/README.md index 70dec3de14..18a8c6d691 100644 --- a/python-sql-libraries/README.md +++ b/python-sql-libraries/README.md @@ -98,4 +98,4 @@ Query executed successfully Query executed successfully ``` -The script stops with a `DuplicateDatabase` error if `sm_app` already exists, so drop it before running the script again with `sudo -u postgres psql -c "DROP DATABASE sm_app"`. +If `sm_app` already exists, the script reports the error and carries on, so the records are inserted a second time. To start over, drop the database with `sudo -u postgres psql -c "DROP DATABASE sm_app"`. diff --git a/python-sql-libraries/mysql_app.py b/python-sql-libraries/mysql_app.py index 70540732ff..8fa00b8a65 100644 --- a/python-sql-libraries/mysql_app.py +++ b/python-sql-libraries/mysql_app.py @@ -210,7 +210,7 @@ def execute_read_query(connection, query): UPDATE posts SET - description = "The weather has become pleasant now" + description = 'The weather has become pleasant now' WHERE id = 2 """ diff --git a/python-sql-libraries/postgresql_app.py b/python-sql-libraries/postgresql_app.py index e434b6c10e..1e56e91732 100644 --- a/python-sql-libraries/postgresql_app.py +++ b/python-sql-libraries/postgresql_app.py @@ -30,7 +30,7 @@ def create_database(connection, query): try: cursor.execute(query) print("Query executed successfully") - except OperationalError as e: + except psycopg2.Error as e: print(f"The error '{e}' occurred") @@ -40,7 +40,7 @@ def execute_query(connection, query): try: cursor.execute(query) print("Query executed successfully") - except OperationalError as e: + except psycopg2.Error as e: print(f"The error '{e}' occurred") @@ -51,7 +51,7 @@ def execute_read_query(connection, query): cursor.execute(query) result = cursor.fetchall() return result - except OperationalError as e: + except psycopg2.Error as e: print(f"The error '{e}' occurred") @@ -180,7 +180,7 @@ def execute_read_query(connection, query): for user in users: print(user) - # Updating table records (PostgreSQL needs single quotes for strings) + # Updating table records update_post_description = """ UPDATE posts diff --git a/python-sql-libraries/sqlite_app.py b/python-sql-libraries/sqlite_app.py index 9d79ec2016..8339298118 100644 --- a/python-sql-libraries/sqlite_app.py +++ b/python-sql-libraries/sqlite_app.py @@ -69,7 +69,7 @@ def execute_read_query(connection, query): text TEXT NOT NULL, user_id INTEGER NOT NULL, post_id INTEGER NOT NULL, - FOREIGN KEY (user_id) REFERENCES users (id) + FOREIGN KEY (user_id) REFERENCES users (id), FOREIGN KEY (post_id) REFERENCES posts (id) ); """ @@ -79,7 +79,7 @@ def execute_read_query(connection, query): id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, post_id integer NOT NULL, - FOREIGN KEY (user_id) REFERENCES users (id) + FOREIGN KEY (user_id) REFERENCES users (id), FOREIGN KEY (post_id) REFERENCES posts (id) ); """ @@ -105,12 +105,12 @@ def execute_read_query(connection, query): INSERT INTO posts (title, description, user_id) VALUES - ("Happy", "I am feeling very happy today", 1), - ("Hot Weather", "The weather is very hot today", 2), - ("Help", "I need some help with my work", 2), - ("Great News", "I am getting married", 1), - ("Interesting Game", "It was a fantastic game of tennis", 5), - ("Party", "Anyone up for a late-night party today?", 3); + ('Happy', 'I am feeling very happy today', 1), + ('Hot Weather', 'The weather is very hot today', 2), + ('Help', 'I need some help with my work', 2), + ('Great News', 'I am getting married', 1), + ('Interesting Game', 'It was a fantastic game of tennis', 5), + ('Party', 'Anyone up for a late-night party today?', 3); """ execute_query(connection, create_posts) @@ -228,7 +228,7 @@ def execute_read_query(connection, query): UPDATE posts SET - description = "The weather has become pleasant now" + description = 'The weather has become pleasant now' WHERE id = 2 """