Adding chapter 4 source code
This commit is contained in:
@@ -0,0 +1 @@
|
||||
Hello WorldEnd
|
||||
@@ -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)
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,2 @@
|
||||
This is a sample file 1
|
||||
This is a test data 1
|
||||
@@ -0,0 +1,2 @@
|
||||
This is a sample file 2
|
||||
This is a test data 2
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,3 @@
|
||||
This is a sample file
|
||||
This is a test data
|
||||
in two lines
|
||||
@@ -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()
|
||||
@@ -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.
|
||||
@@ -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__())
|
||||
@@ -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))
|
||||
@@ -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__())
|
||||
@@ -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))))
|
||||
@@ -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="")
|
||||
@@ -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)
|
||||
@@ -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))
|
||||
@@ -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))
|
||||
@@ -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")
|
||||
@@ -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")
|
||||
@@ -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")
|
||||
@@ -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")
|
||||
@@ -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")
|
||||
@@ -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")
|
||||
@@ -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]
|
||||
@@ -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")
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user