From e8469ec3655c92490506b56c2803ed92863217fa Mon Sep 17 00:00:00 2001 From: muassif <32828975+muassif@users.noreply.github.com> Date: Sun, 21 Feb 2021 19:22:50 +0400 Subject: [PATCH] Adding chapter 4 source code --- chapter4/errors/abc.txt | 1 + chapter4/errors/exception1.py | 15 +++++++++++++ chapter4/errors/exception2.py | 10 +++++++++ chapter4/errors/exception3.py | 18 +++++++++++++++ chapter4/errors/exception4.py | 28 ++++++++++++++++++++++++ chapter4/files/1.txt | 2 ++ chapter4/files/2.txt | 2 ++ chapter4/files/contextmgr1.py | 9 ++++++++ chapter4/files/multifilesread1.py | 6 +++++ chapter4/files/myfile.txt | 3 +++ chapter4/files/writereadfile.py | 16 ++++++++++++++ chapter4/iterators/abc.txt | 4 ++++ chapter4/iterators/generator1.py | 12 ++++++++++ chapter4/iterators/generator2.py | 19 ++++++++++++++++ chapter4/iterators/generator3.py | 7 ++++++ chapter4/iterators/generator4.py | 14 ++++++++++++ chapter4/iterators/iterator1.py | 20 +++++++++++++++++ chapter4/iterators/iterator2.py | 25 +++++++++++++++++++++ chapter4/iterators/iterator3.py | 29 ++++++++++++++++++++++++ chapter4/iterators/iterator4.py | 34 +++++++++++++++++++++++++++++ chapter4/logging/logging1.py | 6 +++++ chapter4/logging/logging2.py | 9 ++++++++ chapter4/logging/logging3.py | 12 ++++++++++ chapter4/logging/logging3A.py | 11 ++++++++++ chapter4/logging/logging4.py | 10 +++++++++ chapter4/logging/logging5.py | 27 +++++++++++++++++++++++ chapter4/logging/logging6.conf.yaml | 26 ++++++++++++++++++++++ chapter4/logging/logging6.py | 15 +++++++++++++ chapter4/logging/logs/logging3.log | 2 ++ chapter4/logging/logs/logging4.log | 6 +++++ chapter4/logging/logs/logging5.log | 3 +++ chapter4/logging/logs/logging6.log | 4 ++++ 32 files changed, 405 insertions(+) create mode 100644 chapter4/errors/abc.txt create mode 100644 chapter4/errors/exception1.py create mode 100644 chapter4/errors/exception2.py create mode 100644 chapter4/errors/exception3.py create mode 100644 chapter4/errors/exception4.py create mode 100644 chapter4/files/1.txt create mode 100644 chapter4/files/2.txt create mode 100644 chapter4/files/contextmgr1.py create mode 100644 chapter4/files/multifilesread1.py create mode 100644 chapter4/files/myfile.txt create mode 100644 chapter4/files/writereadfile.py create mode 100644 chapter4/iterators/abc.txt create mode 100644 chapter4/iterators/generator1.py create mode 100644 chapter4/iterators/generator2.py create mode 100644 chapter4/iterators/generator3.py create mode 100644 chapter4/iterators/generator4.py create mode 100644 chapter4/iterators/iterator1.py create mode 100644 chapter4/iterators/iterator2.py create mode 100644 chapter4/iterators/iterator3.py create mode 100644 chapter4/iterators/iterator4.py create mode 100644 chapter4/logging/logging1.py create mode 100644 chapter4/logging/logging2.py create mode 100644 chapter4/logging/logging3.py create mode 100644 chapter4/logging/logging3A.py create mode 100644 chapter4/logging/logging4.py create mode 100644 chapter4/logging/logging5.py create mode 100644 chapter4/logging/logging6.conf.yaml create mode 100644 chapter4/logging/logging6.py create mode 100644 chapter4/logging/logs/logging3.log create mode 100644 chapter4/logging/logs/logging4.log create mode 100644 chapter4/logging/logs/logging5.log create mode 100644 chapter4/logging/logs/logging6.log diff --git a/chapter4/errors/abc.txt b/chapter4/errors/abc.txt new file mode 100644 index 0000000..fc484cb --- /dev/null +++ b/chapter4/errors/abc.txt @@ -0,0 +1 @@ +Hello WorldEnd \ No newline at end of file diff --git a/chapter4/errors/exception1.py b/chapter4/errors/exception1.py new file mode 100644 index 0000000..4de103c --- /dev/null +++ b/chapter4/errors/exception1.py @@ -0,0 +1,15 @@ +#exception1.py +try: + #print (x) + x = 5 + y = 1 + z = x /y + print('x'+y) + +except NameError as e: + print(e) +except ZeroDivisionError: + print("Division by 0 is not allowed") +except Exception as e: + print("An error occured") + print(e) diff --git a/chapter4/errors/exception2.py b/chapter4/errors/exception2.py new file mode 100644 index 0000000..09a28e7 --- /dev/null +++ b/chapter4/errors/exception2.py @@ -0,0 +1,10 @@ +#exception2.py +try: + f = open("abc.txt", "w") +except Exception as e: + print("Error:" + e) +else: + f.write("Hello World") + f.write("End") +finally: + f.close() \ No newline at end of file diff --git a/chapter4/errors/exception3.py b/chapter4/errors/exception3.py new file mode 100644 index 0000000..c52f667 --- /dev/null +++ b/chapter4/errors/exception3.py @@ -0,0 +1,18 @@ +#exception3.py +import math +def sqrt(num): + + if not isinstance(num, (int, float)) : + raise TypeError("only numbers are allowed") + if num < 0: + raise Exception ("Negative number not supported") + + return math.sqrt(num) + +if __name__ == "__main__": + try: + print(sqrt(9)) + print(sqrt('a')) + print (sqrt(-9)) + except Exception as e: + print(e) \ No newline at end of file diff --git a/chapter4/errors/exception4.py b/chapter4/errors/exception4.py new file mode 100644 index 0000000..ab97fab --- /dev/null +++ b/chapter4/errors/exception4.py @@ -0,0 +1,28 @@ +#exception3.py +import math + +class NumTypeError(TypeError): + pass + +class NegativeNumError(Exception): + def __init__(self): + super().__init__("Negative number not supported") + +def sqrt(num): + + if not isinstance(num, (int, float)) : + raise NumTypeError("only numbers are allowed") + if num < 0: + raise NegativeNumError + + return math.sqrt(num) + +if __name__ == "__main__": + try: + print(sqrt(9)) + print(sqrt('a')) + print (sqrt(-9)) + except NumTypeError as e: + print(e) + except NegativeNumError as e: + print(e) \ No newline at end of file diff --git a/chapter4/files/1.txt b/chapter4/files/1.txt new file mode 100644 index 0000000..6a59ccc --- /dev/null +++ b/chapter4/files/1.txt @@ -0,0 +1,2 @@ +This is a sample file 1 +This is a test data 1 diff --git a/chapter4/files/2.txt b/chapter4/files/2.txt new file mode 100644 index 0000000..bb8ae06 --- /dev/null +++ b/chapter4/files/2.txt @@ -0,0 +1,2 @@ +This is a sample file 2 +This is a test data 2 \ No newline at end of file diff --git a/chapter4/files/contextmgr1.py b/chapter4/files/contextmgr1.py new file mode 100644 index 0000000..2490e10 --- /dev/null +++ b/chapter4/files/contextmgr1.py @@ -0,0 +1,9 @@ +#contextmgr1.py +with open("myfile.txt",'w') as f1: + f1.write("This is a sample file\n") + lines = ["This is a test data\n", "in two lines\n"] + f1.writelines(lines) + +with open("myfile.txt",'r') as f2: + for line in f2.readlines(): + print(line) \ No newline at end of file diff --git a/chapter4/files/multifilesread1.py b/chapter4/files/multifilesread1.py new file mode 100644 index 0000000..c7dd493 --- /dev/null +++ b/chapter4/files/multifilesread1.py @@ -0,0 +1,6 @@ +#multifilesread1.py +import fileinput +with fileinput.input(files = ("1.txt",'2.txt') )as f: + for line in f: + print(f.filename()) + print(line) \ No newline at end of file diff --git a/chapter4/files/myfile.txt b/chapter4/files/myfile.txt new file mode 100644 index 0000000..c110621 --- /dev/null +++ b/chapter4/files/myfile.txt @@ -0,0 +1,3 @@ +This is a sample file +This is a test data +in two lines diff --git a/chapter4/files/writereadfile.py b/chapter4/files/writereadfile.py new file mode 100644 index 0000000..fc8db0d --- /dev/null +++ b/chapter4/files/writereadfile.py @@ -0,0 +1,16 @@ +#writereadfile.pywrite to a file and then read from it +f1 = open("myfile.txt",'w') +f1.write("This is a sample file\n") +lines =["This is a test data\n", "in two lines\n"] +f1.writelines(lines) +f1.close() + +f2 = open("myfile.txt",'r') +print(f2.read(4)) +print(f2.readline()) +print(f2.readline()) + +f2.seek(0) +for line in f2.readlines(): + print(line) +f2.close() \ No newline at end of file diff --git a/chapter4/iterators/abc.txt b/chapter4/iterators/abc.txt new file mode 100644 index 0000000..e993b46 --- /dev/null +++ b/chapter4/iterators/abc.txt @@ -0,0 +1,4 @@ +Iteration is one of the key tools used for data processing and data transformation. +The iterations are especially useful when dealing with large datasets and bringing +the whole dataset into the memory is not possible or efficient. Iterators provide +a way to bring the data into memory one item at a time. \ No newline at end of file diff --git a/chapter4/iterators/generator1.py b/chapter4/iterators/generator1.py new file mode 100644 index 0000000..da760b3 --- /dev/null +++ b/chapter4/iterators/generator1.py @@ -0,0 +1,12 @@ +#generators1.py +def my_gen(): + yield 'A' + yield 'B' + yield 'C' + + +if(__name__ == "__main__"): + iter1 = my_gen() + print(iter1.__next__()) + print(next(iter1)) + print(iter1.__next__()) diff --git a/chapter4/iterators/generator2.py b/chapter4/iterators/generator2.py new file mode 100644 index 0000000..61278cb --- /dev/null +++ b/chapter4/iterators/generator2.py @@ -0,0 +1,19 @@ +#generator2.py +class Week: + def __init__(self): + self.days = {1:'Monday', 2: "Tuesday", + 3:"Wednesday", 4: "Thursday", + 5:"Friday", 6:"Saturday", 7:"Sunday"} + + def week_gen(self): + for x in self.days: + yield self.days[x] + +if(__name__ == "__main__"): + wk = Week() + iter1 = wk.week_gen() + iter2 = iter(wk.week_gen()) + print(iter1.__next__()) + print(iter2.__next__()) + print(next(iter1)) + print(next(iter2)) \ No newline at end of file diff --git a/chapter4/iterators/generator3.py b/chapter4/iterators/generator3.py new file mode 100644 index 0000000..8053045 --- /dev/null +++ b/chapter4/iterators/generator3.py @@ -0,0 +1,7 @@ +#generator3.py +L = [1,2,3,4,5,6,7,8,9,0] +f1 = [x+1 for x in L] +g1 = (x+1 for x in L) + +print(g1.__next__()) +print(g1.__next__()) diff --git a/chapter4/iterators/generator4.py b/chapter4/iterators/generator4.py new file mode 100644 index 0000000..1730bfb --- /dev/null +++ b/chapter4/iterators/generator4.py @@ -0,0 +1,14 @@ +#generator4.py +def prime_gen(num): + for cand in range(2, num+1): + for i in range (2, cand): + if (cand % i) == 0: + break + else: + yield cand + +def x2_gen(list2): + for num in list2: + yield num*num + +print(sum(x2_gen(prime_gen(5)))) diff --git a/chapter4/iterators/iterator1.py b/chapter4/iterators/iterator1.py new file mode 100644 index 0000000..8e1932a --- /dev/null +++ b/chapter4/iterators/iterator1.py @@ -0,0 +1,20 @@ +#iterator1.py +#example 1: iterating on a list +for x in [1,2,3]: + print(x) + +#example 2: iterating on a string +for x in "Python for Geeks": + print(x, end="") +print('') + +#example 3: iterating on a dictionary +week_days = {1:'Mon', 2:'Tue', + 3:'Wed', 4:'Thu', + 5:'Fri', 6:'Sat', 7:'Sun'} +for k in week_days: + print(k, week_days[k]) + +#example 4: iterating on a file +for row in open('abc.txt'): + print(row, end="") \ No newline at end of file diff --git a/chapter4/iterators/iterator2.py b/chapter4/iterators/iterator2.py new file mode 100644 index 0000000..b08a187 --- /dev/null +++ b/chapter4/iterators/iterator2.py @@ -0,0 +1,25 @@ +#iterator2.py +class Week: + def __init__(self): + self.days = {1:'Monday', 2: "Tuesday", + 3:"Wednesday", 4: "Thursday", + 5:"Friday", 6:"Saturday", 7:"Sunday"} + self._index = 1 + + def __iter__(self): + self._index = 1 + return self + + def __next__(self): + + if self._index < 1 | self._index > 8: + raise StopIteration + else: + ret_value = self.days[self._index] + self._index +=1 + return ret_value + +if(__name__ == "__main__"): + wk = Week() + for day in wk: + print(day) \ No newline at end of file diff --git a/chapter4/iterators/iterator3.py b/chapter4/iterators/iterator3.py new file mode 100644 index 0000000..dcd460c --- /dev/null +++ b/chapter4/iterators/iterator3.py @@ -0,0 +1,29 @@ +#iterator3.py +class Week: + def __init__(self): + self.days = {1:'Monday', 2: "Tuesday", + 3:"Wednesday", 4: "Thursday", + 5:"Friday", 6:"Saturday", 7:"Sunday"} + self._index = 1 + + def __iter__(self): + self._index = 1 + return self + + def __next__(self): + + if self._index < 1 | self._index > 8: + raise StopIteration + else: + ret_value = self.days[self._index] + self._index +=1 + return ret_value + +if(__name__ == "__main__"): + wk = Week() + iter1 = iter(wk) + iter2 = iter(wk) + print(iter1.__next__()) + print(iter2.__next__()) + print(next(iter1)) + print(next(iter2)) diff --git a/chapter4/iterators/iterator4.py b/chapter4/iterators/iterator4.py new file mode 100644 index 0000000..98a1631 --- /dev/null +++ b/chapter4/iterators/iterator4.py @@ -0,0 +1,34 @@ +#iterator4.py +class Week: + def __init__(self): + self.days = {1: 'Monday', 2: "Tuesday", + 3: "Wednesday", 4: "Thursday", + 5: "Friday", 6: "Saturday", 7: "Sunday"} + + def __iter__(self): + return WeekIterator(self.days) + +class WeekIterator: + def __init__(self, dayss): + self.days_ref = dayss + self._index = 1 + + def __iter__(self): + return self; + + def __next__(self): + if self._index < 1 | self._index > 8: + raise StopIteration + else: + ret_value = self.days_ref[self._index] + self._index +=1 + return ret_value + +if(__name__ == "__main__"): + wk = Week() + iter1 = iter(wk) + iter2 = iter(wk) + print(iter1.__next__()) + print(iter2.__next__()) + print(next(iter1)) + print(next(iter2)) \ No newline at end of file diff --git a/chapter4/logging/logging1.py b/chapter4/logging/logging1.py new file mode 100644 index 0000000..fcec7af --- /dev/null +++ b/chapter4/logging/logging1.py @@ -0,0 +1,6 @@ +#logging1.py +import logging +#logging.basicConfig(level=logging.DEBUG) +logging.debug("This is a debug message") +logging.warning("This is a warning message") +logging.info("This is an info message") \ No newline at end of file diff --git a/chapter4/logging/logging2.py b/chapter4/logging/logging2.py new file mode 100644 index 0000000..af163e8 --- /dev/null +++ b/chapter4/logging/logging2.py @@ -0,0 +1,9 @@ +#logging2.py +import logging +logger1 = logging.getLogger("my_logger") +logging.basicConfig() +logger1.setLevel(logging.INFO) +logger1.warning("This is a warning message") +logger1.info("This is a info message") +logger1.debug("This is a debug messag") +logging.info("This is an info message") diff --git a/chapter4/logging/logging3.py b/chapter4/logging/logging3.py new file mode 100644 index 0000000..55182d5 --- /dev/null +++ b/chapter4/logging/logging3.py @@ -0,0 +1,12 @@ +#logging3.py +import logging +logger = logging.getLogger('my_logger') +my_handler = logging.StreamHandler() +my_formatter = logging.Formatter('%(asctime)s - ' + '%(name)s - %(levelname)s - %(message)s') +my_handler.setFormatter(my_formatter) +logger.addHandler(my_handler) +logger.setLevel(logging.INFO) +logger.warning("This is a warning message") +logger.info("This is an info message") +logger.debug("This is a debug message") \ No newline at end of file diff --git a/chapter4/logging/logging3A.py b/chapter4/logging/logging3A.py new file mode 100644 index 0000000..c017bba --- /dev/null +++ b/chapter4/logging/logging3A.py @@ -0,0 +1,11 @@ +#logging3A.py +import logging +logger = logging.getLogger('my_logger') +logging.basicConfig(handlers=[logging.StreamHandler()], + format="%(asctime)s - %(name)s - " + "%(levelname)s - %(message)s", + level=logging.INFO) + +logger.warning("This is a warning message") +logger.info("This is an info message") +logger.debug("This is a debug message") \ No newline at end of file diff --git a/chapter4/logging/logging4.py b/chapter4/logging/logging4.py new file mode 100644 index 0000000..2b09088 --- /dev/null +++ b/chapter4/logging/logging4.py @@ -0,0 +1,10 @@ +#logging4.py +import logging + +logging.basicConfig(filename='logs/logging4.log' + ,level=logging.DEBUG) +logger = logging.getLogger('my_logger') +logger.setLevel(logging.INFO) +logger.warning("This is a warning message") +logger.info("This is a info message") +logger.debug("This is a debug message") \ No newline at end of file diff --git a/chapter4/logging/logging5.py b/chapter4/logging/logging5.py new file mode 100644 index 0000000..e136c29 --- /dev/null +++ b/chapter4/logging/logging5.py @@ -0,0 +1,27 @@ +#logging5.py +import logging +logger = logging.getLogger('my_logger') +logger.setLevel(logging.DEBUG) +console_handler = logging.StreamHandler() +file_handler = logging.FileHandler("logs/logging5.log") +#setting logging levels at the handler level +console_handler.setLevel(logging.DEBUG) +file_handler.setLevel(logging.INFO) + +#creating separate formatter for two handlers +console_formatter = logging.Formatter( + '%(name)s - %(levelname)s - %(message)s') +file_formatter = logging.Formatter('%(asctime)s - ' + '%(name)s - %(levelname)s - %(message)s') + +#adding formatters to the handler +console_handler.setFormatter(console_formatter) +file_handler.setFormatter(file_formatter) +#adding handlers to the logger +logger.addHandler(console_handler) +logger.addHandler(file_handler) + +logger.error("This is an error message") +logger.warning("This is a warning message") +logger.info("This is a info message") +logger.debug("This is a debug message") \ No newline at end of file diff --git a/chapter4/logging/logging6.conf.yaml b/chapter4/logging/logging6.conf.yaml new file mode 100644 index 0000000..57e9e1f --- /dev/null +++ b/chapter4/logging/logging6.conf.yaml @@ -0,0 +1,26 @@ +version: 1 +formatters: + console_formatter: + format: '%(name)s - %(levelname)s - %(message)s' + file_formatter: + format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' +handlers: + console_handler: + class: logging.StreamHandler + level: DEBUG + formatter: console_formatter + stream: ext://sys.stdout + + file_handler: + class: logging.FileHandler + level: INFO + formatter: file_formatter + filename: logs/logging6.log +loggers: + my_logger: + level: DEBUG + handlers: [console_handler, file_handler] + propagate: no +root: + level: ERROR + handlers: [console_handler] \ No newline at end of file diff --git a/chapter4/logging/logging6.py b/chapter4/logging/logging6.py new file mode 100644 index 0000000..d10e681 --- /dev/null +++ b/chapter4/logging/logging6.py @@ -0,0 +1,15 @@ +#logging6.py +import logging +import logging.config +import yaml + +with open('logging6.conf.yaml', 'r') as f: + config = yaml.safe_load(f.read()) + logging.config.dictConfig(config) + +logger = logging.getLogger('my_logger') + +logger.error("This is an error message") +logger.warning("This is a warning message") +logger.info("This is a info message") +logger.debug("This is a debug message") \ No newline at end of file diff --git a/chapter4/logging/logs/logging3.log b/chapter4/logging/logs/logging3.log new file mode 100644 index 0000000..53f0253 --- /dev/null +++ b/chapter4/logging/logs/logging3.log @@ -0,0 +1,2 @@ +2021-02-02 16:56:14,794 - my_logger - WARNING - This is a warning message +2021-02-02 16:56:14,794 - my_logger - INFO - This is a info message diff --git a/chapter4/logging/logs/logging4.log b/chapter4/logging/logs/logging4.log new file mode 100644 index 0000000..7ce349d --- /dev/null +++ b/chapter4/logging/logs/logging4.log @@ -0,0 +1,6 @@ +WARNING:my_logger:This is a warning message +INFO:my_logger:This is a info message +WARNING:my_logger:This is a warning message +INFO:my_logger:This is a info message +WARNING:my_logger:This is a warning message +INFO:my_logger:This is a info message diff --git a/chapter4/logging/logs/logging5.log b/chapter4/logging/logs/logging5.log new file mode 100644 index 0000000..cf11996 --- /dev/null +++ b/chapter4/logging/logs/logging5.log @@ -0,0 +1,3 @@ +2021-02-02 17:57:27,716 - my_logger - ERROR - This is an error message +2021-02-02 17:57:27,716 - my_logger - WARNING - This is a warning message +2021-02-02 17:57:27,716 - my_logger - INFO - This is a info message diff --git a/chapter4/logging/logs/logging6.log b/chapter4/logging/logs/logging6.log new file mode 100644 index 0000000..e7cab09 --- /dev/null +++ b/chapter4/logging/logs/logging6.log @@ -0,0 +1,4 @@ + +2021-02-02 18:35:45,372 - my_logger - ERROR - This is an error message +2021-02-02 18:35:45,373 - my_logger - WARNING - This is a warning message +2021-02-02 18:35:45,373 - my_logger - INFO - This is a info message