From e42f61d34702d99e109ad2d303371479f807772a Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 5 Mar 2026 21:33:38 +0530 Subject: [PATCH 001/132] Update README.md --- README.md | 6 ------ 1 file changed, 6 deletions(-) diff --git a/README.md b/README.md index a2f7d14..bc8d9a9 100644 --- a/README.md +++ b/README.md @@ -92,12 +92,6 @@ Open a Pull Request. --- -## 📝 License - -Distributed under the MIT License. See `LICENSE` for more information. - ---- -

Developed with ❤️ by Hemanth

From 4222eb7e9bae9d9fab4c8a95366a8b68ecc2eb63 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 5 Mar 2026 22:50:47 +0530 Subject: [PATCH 002/132] Create metaclass with inheritance.py --- unit_2/metaclass with inheritance.py | 32 ++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 unit_2/metaclass with inheritance.py diff --git a/unit_2/metaclass with inheritance.py b/unit_2/metaclass with inheritance.py new file mode 100644 index 0000000..418d6f3 --- /dev/null +++ b/unit_2/metaclass with inheritance.py @@ -0,0 +1,32 @@ +import os +os.system('cls') + +class CMeta(type): + def __new__(cls, n, b, d): + print(f'Creating a class {n}') + d['Created_by'] = 'CMeta' + d['Created_on'] = '14 November' + return super().__new__(cls, n, b, d) + +# Use Metaclass Keyword +class ExampleA(metaclass = CMeta): + def greet(self): + print('Hello from ExampleA') + +# Inheriting from a class that uses the custom metaclass +class ExampleB(ExampleA): + def greet(self): + print('Hello from ExampleB') + +ExampleA().greet() +ExampleB().greet() + +# Check for the attributes added by the custom Metaclass +print(ExampleA().Created_on) +print(ExampleA().Created_by) + +class ExampleC(ExampleB): + def greet(self): + print('Hello from ExampleC') + +print(ExampleC().Created_on) From b700cb6ba6049b7ee5e54ebd80436ba87c0b0c9f Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 5 Mar 2026 22:51:21 +0530 Subject: [PATCH 003/132] Create metaclasses.py --- unit_2/metaclasses.py | 61 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 unit_2/metaclasses.py diff --git a/unit_2/metaclasses.py b/unit_2/metaclasses.py new file mode 100644 index 0000000..e33fa12 --- /dev/null +++ b/unit_2/metaclasses.py @@ -0,0 +1,61 @@ +import os +os.system('cls') + +# Creation of a class using type +def greet(self): + print(f'Hello {self.name}') + +# Create the class and attach the method to the class +Student = type('Student', (object,), {'greet':greet, 'name':'XYZ'}) +'''type takes in three parameters + name - name of the class + base - tuple that consists of the base classes + dictionary - a key vvalue pair of every method and attribute''' + +# Create the object of the class +s = Student() +print(type(s)) + +# Creation of Custom Metaclass +class RequiredID(type): + '''To create a metaclass it has to inherit from type + type builds classes''' + def __new__(cls, name, bases, attr): + '''custom new method is defined + parameters are + cls - metaclass itself + name - name of the class being created + bases - tuple of base class + attr - dictionary of attributes and method of the class''' + if 'id' not in attr: + attr['id'] = 100 + '''Check whether an attribute called as id exists + if the class does not define id a default attribute if is added with a value of 100''' + return super().__new__(cls, name, bases, attr) + '''Calling types's new method''' + +# Create a class that uses custom meta class + +class Student(metaclass = RequiredID): + '''metaclass = Required tells Python to use + RequiredID as the metaclass and not the default metaclass + name - Student + bases - empty tuple since it does not inherit any other + class except the metaclass + attr - should be the dictionary of attributes and methods. + In this example keep it empty''' + def __init__(self, name): + self.name = name + +s = Student('ABC') +print(s.name) +print(s.id) + +class Teacher(metaclass = RequiredID): + id = 20 + def __init__(self, name): + self.name = name + +t = Teacher('BAA') +print(t.name) +print(t.id) From 396b13ac39a0acf0e1d06a9fd4925cf0db4e7c8a Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 5 Mar 2026 22:52:04 +0530 Subject: [PATCH 004/132] Create new() Class.py --- unit_2/new() Class.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 unit_2/new() Class.py diff --git a/unit_2/new() Class.py b/unit_2/new() Class.py new file mode 100644 index 0000000..b856a01 --- /dev/null +++ b/unit_2/new() Class.py @@ -0,0 +1,22 @@ +import os +os.system('cls') + + +class NewClass1: + def __new__(cls, a): + # a is the placeholder for 'b' that is used for initiaizing the object. + # The number of attributes that is used to correspond to the number of attributes in init. + print('------------- Inside new method -------------') + i = super().__new__(cls) + '''super() refers to the parent class which is the built-in object class + equivalent to object.__new__(cls) + creates a new, empty instance of cls''' + return i + def __init__(self, b): + print('Inside init method') + self.b = b + def show(self): + print(f'The stored value is {self.b}') + +y = NewClass1(10) +y.show() From de8d42afe42c5c1060cdd969ef1da07b491daed7 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 5 Mar 2026 22:52:52 +0530 Subject: [PATCH 005/132] Create static and class method.py --- unit_2/static and class method.py | 63 +++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 unit_2/static and class method.py diff --git a/unit_2/static and class method.py b/unit_2/static and class method.py new file mode 100644 index 0000000..faf1714 --- /dev/null +++ b/unit_2/static and class method.py @@ -0,0 +1,63 @@ +# Static Methods +class NewClass: + val = 0 + + def __init__(self, value): + self.value = value + + @staticmethod + def count(): + NewClass.val += 1 + def show(self): + print(f'The number of objects created is {NewClass.val}') + +o = NewClass(10) +o.count() +o.show() + +NewClass(20).count() +NewClass(20).show() + +o.count() + +# Class Methods +class NewClass: + val = 10 + def __init__(self, a, b): + self.a = a + self.b = b + + @classmethod + def incr(cls, x): + cls.val += x + + def show(self): + print(f'The attribute is {self.a}, {self.b}, the value is {NewClass.val}') + +z = NewClass(10, 3) +z.incr(10) +z.show() + +z1 = NewClass('Hello', 'python!!') +z1.incr(25) +z1.show() + +z.show() + +# New() +class NewClass1: + def __new__(cls, a): + print('------------- Inside new method -------------') + i = super().__new__(cls) + '''super() refers to the parent class which is the built-in object class + equivalent to object.__new__(cls) + creates a new, empty instance of cls''' + return i + def __init__(self, b): + print('Inside init method') + self.b = b + def show(self): + print(f'The stored value is {self.b}') + +y = NewClass1(10) +y.show() From 6f7c9edc848f1d69f8d95a90166cd674dbaab41f Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 5 Mar 2026 22:54:22 +0530 Subject: [PATCH 006/132] Delete userStrings.py --- userStrings.py | 19 ------------------- 1 file changed, 19 deletions(-) delete mode 100644 userStrings.py diff --git a/userStrings.py b/userStrings.py deleted file mode 100644 index 82c008d..0000000 --- a/userStrings.py +++ /dev/null @@ -1,19 +0,0 @@ -from collections import UserString - -#---- Create Custom String of the type UserString -class MyString(UserString): - def uppercon(self): - return self.upper() - def add_exclamation(self): - return self.data + '!!!' - -#--- Create an instance of Custom String -cs = MyString("Hello, how are you") -print(cs) - -#--- Custom Methods -print(cs.uppercon()) -print(id(cs)) - -cs = cs.add_exclamation() -print(cs) \ No newline at end of file From 4e467654654fcd55959198f6f49fa37f8c79a0cd Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 5 Mar 2026 22:54:36 +0530 Subject: [PATCH 007/132] Delete expLearn1_1.py --- expLearn1_1.py | 19 ------------------- 1 file changed, 19 deletions(-) delete mode 100644 expLearn1_1.py diff --git a/expLearn1_1.py b/expLearn1_1.py deleted file mode 100644 index 15d6635..0000000 --- a/expLearn1_1.py +++ /dev/null @@ -1,19 +0,0 @@ -# Import Counter class from collections module -from collections import Counter - -# Step 1: Ask user to enter a string -user_input = input("Enter a string: ") - -# Step 2: Create a Counter object to count each character -# Counter works like a dictionary where: -# key = character -# value = how many times that character appears -character_count = Counter(user_input) -print(f'{character_count}') -print("\nCharacters that appear more than 2 times:\n") - -for character in character_count: - count = character_count[character] # get frequency of that character - - if count > 1: - print(f"The character '{character}' appears {count} times.") From e1814a57b6939a7fda1b45e3922b01fb263d16d7 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 5 Mar 2026 22:59:50 +0530 Subject: [PATCH 008/132] Create custom Objects.py --- unit_3/packing and unpacking/custom Objects.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 unit_3/packing and unpacking/custom Objects.py diff --git a/unit_3/packing and unpacking/custom Objects.py b/unit_3/packing and unpacking/custom Objects.py new file mode 100644 index 0000000..b0621aa --- /dev/null +++ b/unit_3/packing and unpacking/custom Objects.py @@ -0,0 +1,17 @@ +import pickle as p + +class Person: + def __init__(self, name, age): + self.name = name + self.age = age + + def __repr__(self): + return f'Person(name: {self.name}, age: {self.age})' + +p1 = Person('Alpha', 24) + +with open('obj.pkl', 'wb') as f: + p.dump(p1, f) +with open('obj.pkl', 'rb') as f: + p_obj = p.load(f) +print(f'Unpickled object is: {p_obj}') From 2f69b7a545c77806dbee75d069a4129236dca8dd Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 5 Mar 2026 23:00:23 +0530 Subject: [PATCH 009/132] Create Data Frames.py --- unit_3/packing and unpacking/Data Frames.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 unit_3/packing and unpacking/Data Frames.py diff --git a/unit_3/packing and unpacking/Data Frames.py b/unit_3/packing and unpacking/Data Frames.py new file mode 100644 index 0000000..ff8e877 --- /dev/null +++ b/unit_3/packing and unpacking/Data Frames.py @@ -0,0 +1,17 @@ +import pickle as p +import pandas as pd + +# Data Frames + +data = {'Name': ['Alpha', 'Beta', 'Gamma'], + 'Age': [12, 34, 67], + 'City': ['Bangalore', 'Mangalore', 'Mysore']} + +df = pd.DataFrame(data) +print(df) +print(type(df)) + +df.to_pickle('df.pkl') +p_df = pd.read_pickle('df.pkl') +print(p_df) +print(type(p_df)) From 9469f036f888dc05e90c37948f4281551b82dcf6 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 5 Mar 2026 23:01:19 +0530 Subject: [PATCH 010/132] Create Dictionary pickling.py --- unit_3/packing and unpacking/Dictionary pickling.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 unit_3/packing and unpacking/Dictionary pickling.py diff --git a/unit_3/packing and unpacking/Dictionary pickling.py b/unit_3/packing and unpacking/Dictionary pickling.py new file mode 100644 index 0000000..4bcbd2b --- /dev/null +++ b/unit_3/packing and unpacking/Dictionary pickling.py @@ -0,0 +1,8 @@ +import pickle as p + +d_1 = {'name':'Alpha', 'age':20, 'city':'Bangalore', 'phone': 9876543210} +with open("dict.pkl", 'wb') as f: + p.dump(d_1, f) +with open("dict.pkl", 'rb') as f: + p_d_1 = p.load(f) +print(f'Unpickled dictionary is {p_d_1}') From 71425474150076c8b22a33c47ec69460edbc8ed9 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 5 Mar 2026 23:01:53 +0530 Subject: [PATCH 011/132] Create Functions pickling.py --- unit_3/packing and unpacking/Functions pickling.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 unit_3/packing and unpacking/Functions pickling.py diff --git a/unit_3/packing and unpacking/Functions pickling.py b/unit_3/packing and unpacking/Functions pickling.py new file mode 100644 index 0000000..e4b72ec --- /dev/null +++ b/unit_3/packing and unpacking/Functions pickling.py @@ -0,0 +1,12 @@ +import pickle as p + +def greet(name): + return f'Hello {name}' + +with open('func.pkl', 'wb') as f: + p.dump(greet, f) + +with open('func.pkl', 'rb') as f: + p_f = p.load(f) + +print(p_f('Alpha'), p_f('Beta')) From 495c24ef865ae393cc8b2b66ed22d69e5b8663a5 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 5 Mar 2026 23:02:30 +0530 Subject: [PATCH 012/132] Create Lists pickling.py --- unit_3/packing and unpacking/Lists pickling.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 unit_3/packing and unpacking/Lists pickling.py diff --git a/unit_3/packing and unpacking/Lists pickling.py b/unit_3/packing and unpacking/Lists pickling.py new file mode 100644 index 0000000..c6b3540 --- /dev/null +++ b/unit_3/packing and unpacking/Lists pickling.py @@ -0,0 +1,11 @@ +import pickle as p + +l1= ['apple', 23, 56, 78, 'BANANA', 89-9j, ['a', 'b','c']] +with open('list.pkl', 'wb') as f: + p.dump(l1, f) + +with open('list.pkl', 'rb') as f: + p_l1 = p.load(f) +print(f'Unpickled list is {p_l1}') +print(f'Type of p_l1 is {type(p_l1)}') +print(f'Type of "f" is {type(f)} and type of "list.pkl" is {type("list.pkl")}') From fb9723e696f045df64f68432984f16ebeaad3dcf Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 5 Mar 2026 23:03:06 +0530 Subject: [PATCH 013/132] Create Loads and Dumps.py --- .../packing and unpacking/Loads and Dumps.py | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 unit_3/packing and unpacking/Loads and Dumps.py diff --git a/unit_3/packing and unpacking/Loads and Dumps.py b/unit_3/packing and unpacking/Loads and Dumps.py new file mode 100644 index 0000000..be8694b --- /dev/null +++ b/unit_3/packing and unpacking/Loads and Dumps.py @@ -0,0 +1,20 @@ +import pickle as p + +# Load and dumps + +# dump - seralize the data into a file +# load - deserialize data from a file +# dumps - serialize the data as byte in memory +# loads - deserialize bytes into data + +a = 10 +p_a = p.dumps(a) +print(p_a, type(p_a)) +print(p.loads(p_a), type(p_a)) + +b, c, d = 45.7, 9+0j, "Hello" +p_b = p.dumps(b) +p_c = p.dumps(c) +p_d = p.dumps(d) + +print(f'Deserialized data is {p.loads(p_b)}, {p.loads(p_c)}, {p.loads(p_d)}') From 7ff51f145bc236419db051bc7ba45ede8ad0a907 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 5 Mar 2026 23:03:38 +0530 Subject: [PATCH 014/132] Create Multiple Objects.py --- .../packing and unpacking/Multiple Objects.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 unit_3/packing and unpacking/Multiple Objects.py diff --git a/unit_3/packing and unpacking/Multiple Objects.py b/unit_3/packing and unpacking/Multiple Objects.py new file mode 100644 index 0000000..4d04308 --- /dev/null +++ b/unit_3/packing and unpacking/Multiple Objects.py @@ -0,0 +1,17 @@ +import pickle as p + +# Multiple Objects +l1 = [1, 2, 3, 'apple', [2, 3, 4], 89+9j] +d1 = {1:2, 3:4} +s1 = 'Hello Pickling' +with open('all.pkl', 'wb') as f: + p.dump(l1, f) + p.dump(d1, f) + p.dump(s1, f) +with open('all.pkl', 'rb') as f: + p_l1 = p.load(f) + p_d1 = p.load(f) + p_s1 = p.load(f) +print(p_l1) +print(p_d1) +print(p_s1) From 82c9c97eb9bba472047a912968a822eca670942f Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 5 Mar 2026 23:04:11 +0530 Subject: [PATCH 015/132] Create Numeric DataType.py --- unit_3/packing and unpacking/Numeric DataType.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 unit_3/packing and unpacking/Numeric DataType.py diff --git a/unit_3/packing and unpacking/Numeric DataType.py b/unit_3/packing and unpacking/Numeric DataType.py new file mode 100644 index 0000000..ceefc9b --- /dev/null +++ b/unit_3/packing and unpacking/Numeric DataType.py @@ -0,0 +1,15 @@ +import pickle as p + +# Numeric DataType + +a, b, c = 10, 10.5, 10-9j + +with open('numeric.pkl', 'wb') as f: + ''' Use wb since the data has to be writte in bytestream''' + p.dump(a, f) + p.dump(b, f) + p.dump(c, f) + +with open('numeric.pkl', 'rb') as f: + data = p.load(f) + print(f'Unpickled data is {data}') From c200cb21c0876f750669e677efd3eb9f8b24b729 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 22:55:28 +0530 Subject: [PATCH 016/132] Create assertionError.py --- unit_3/assertionError.py | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 unit_3/assertionError.py diff --git a/unit_3/assertionError.py b/unit_3/assertionError.py new file mode 100644 index 0000000..8c45a2f --- /dev/null +++ b/unit_3/assertionError.py @@ -0,0 +1,7 @@ +def division(a,b): + assert b != 0 + return a/b + +print(division(10,2)) +print(division(10,0.5)) +print(division(10,0)) # AssertionError From 338e866c2a9cb5556c5fcf7c58be7bc421d1f665 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 22:56:03 +0530 Subject: [PATCH 017/132] Create attributeError.py --- unit_3/attributeError.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 unit_3/attributeError.py diff --git a/unit_3/attributeError.py b/unit_3/attributeError.py new file mode 100644 index 0000000..1422ad4 --- /dev/null +++ b/unit_3/attributeError.py @@ -0,0 +1,12 @@ +# s = "Hello to Errors" +# s.reverse() + +class Person: + def __init__(self, name, age): + self.name = name + self.age = age + def greet(self): + print(f'Hello, My name is {self.name})') + +p = Person('Ironman', 40) +p.city # AttributeError: 'Person' object has no attribute 'city' From 6fd150a8302ea9cdaf056ffe6b0f420f1a1f3d74 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 22:56:33 +0530 Subject: [PATCH 018/132] Create creating a new worksheet.py --- unit_3/creating a new worksheet.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 unit_3/creating a new worksheet.py diff --git a/unit_3/creating a new worksheet.py b/unit_3/creating a new worksheet.py new file mode 100644 index 0000000..53da363 --- /dev/null +++ b/unit_3/creating a new worksheet.py @@ -0,0 +1,25 @@ +import openpyxl as op + +wb = op.load_workbook('.\VideoSales.xlsx') +ws = wb.active +# ws = wb['SalesData'] +# wb.create_sheet('New Sheet') +# wb.save('VideoSales.xlsx') +# print(wb.sheetnames) + +# --------- Title of active sheet ------------- +print(ws.title) + +# --------- Rename a sheet ---------------- +# ws = wb['New Sheet1'] +# print(ws.title) +ws.title = 'A New Sheet' +# wb.save('VideoSales.xlsx') +# print(wb.sheetnames) +print(wb.sheetnames) + +# Duplicate a worksheet +new_ws = wb.copy_worksheet(wb['A New Sheet1']) +new_ws.title = 'A New Sheet' +wb.save('VideoSales.xlsx') +print(wb.sheetnames) From c361555eb66f689e1bb955f1d87db2511ef2c498 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 22:57:05 +0530 Subject: [PATCH 019/132] Create CSV_data_frame.py --- unit_3/CSV_data_frame.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 unit_3/CSV_data_frame.py diff --git a/unit_3/CSV_data_frame.py b/unit_3/CSV_data_frame.py new file mode 100644 index 0000000..c736a09 --- /dev/null +++ b/unit_3/CSV_data_frame.py @@ -0,0 +1,36 @@ +import pandas as pd + +sd = pd.read_csv('sales_demo.csv') +pr = pd.read_csv('products_demo.csv') + +print(type(sd), type(pr)) + +print(sd.shape) +print(pr.shape) + +print(sd.columns) + +print(pr['ProductID'].nunique()) +print(len(pr)) + +df = pd.merge(sd, pr, on = "ProductID", how = "inner") +print(df.shape) + +m_left = pd.merge(sd, pr, on = "ProductID", how = "left") +m_left1 = pd.merge(pr, sd, on = "ProductID", how = "left") + +print(m_left.shape, m_left1.shape) + +m_right = pd.merge(sd, pr, on = "ProductID", how = "right") +m_right1 = pd.merge(pr, sd, on = "ProductID", how = "right") + +print(m_right.shape, m_right1.shape) +m_outer = pd.merge(sd, pr, on = "ProductID", how = "outer") +m_outer1 = pd.merge(pr, sd, on = "ProductID", how = "outer") +print(m_outer.shape, m_outer1.shape) +print(m_outer, m_outer1) + +''' Inner join - common records from both data frames + Outer join - all reccords from both data frames + Left join - all records of left data frames + Right join - all records of right data frames''' From b195fa5b2d766185649d7ff9841c380d98dee3d1 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 22:57:56 +0530 Subject: [PATCH 020/132] Create expeption Handling.py --- unit_3/expeption Handling.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 unit_3/expeption Handling.py diff --git a/unit_3/expeption Handling.py b/unit_3/expeption Handling.py new file mode 100644 index 0000000..52826cf --- /dev/null +++ b/unit_3/expeption Handling.py @@ -0,0 +1,23 @@ +# Try and Except block + +n = int(input("Enter the numerator: ")) +try: + d = int(input("Enter the denominator: ")) + print(n/d) +except ZeroDivisionError as e: + print(f'ZeroDivisionError: {e}') + +n = int(input("Enter the numerator: ")) +d = int(input("Enter the denominator: ")) +print(n/d) + + +# Try except and else block + +try: + n = int(input("Enter a number: ")) + assert n%2 == 0 +except: + print("Not an even number") +else: + print(n/4) From 7b74739e43fcca60e862eeefdcf629927fd100d6 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 22:58:31 +0530 Subject: [PATCH 021/132] Create expection Handling finally.py --- unit_3/expection Handling finally.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 unit_3/expection Handling finally.py diff --git a/unit_3/expection Handling finally.py b/unit_3/expection Handling finally.py new file mode 100644 index 0000000..af0d859 --- /dev/null +++ b/unit_3/expection Handling finally.py @@ -0,0 +1,10 @@ +n = int(input("Enter the numerator: ")) +try: + d = int(input("Enter the denominator: ")) + print(n/d) +except: + print("Error: Denominator cannot be a zero") +finally: + print("Division may have occurred") + ''' finally block is executed if the exception is identifed and handled + finally block is executed if the exception does not occur also''' From a26318df8a1a1ba8691f2a01e7bc763d522942d6 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 22:59:02 +0530 Subject: [PATCH 022/132] Create file excel handling.py --- unit_3/file excel handling.py | 100 ++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 unit_3/file excel handling.py diff --git a/unit_3/file excel handling.py b/unit_3/file excel handling.py new file mode 100644 index 0000000..5652327 --- /dev/null +++ b/unit_3/file excel handling.py @@ -0,0 +1,100 @@ +import openpyxl as op +# load the workbook +wb = op.load_workbook('.\VideoSales.xlsx') +# print(type(wb)) # + +# print(wb) # + +# Call the active worksheet +ws = wb.active +# print(type(ws)) + +# Call the sheet by it's name +ws = wb['SalesData'] +# print(ws) # + +# Count the number of rows and columns that are filled in the worksheet +# print(f'Total number of rows is {ws.max_row} and total number of columns is {ws.max_column}') + +# Read the data from a cell +# print(f"The value stored in cell D5 is: {ws['D5'].value}") + +# Read data from multiple cells +values = [ + ws.cell(row = 1, column = i).value + for i in range(1, ws.max_column + 1) +] +# print(values) + +data = [ + ws.cell(row = 1, column = i).value + for i in range(1, ws.max_column + 1) +] +# print(values) + +# Reading data from a range of cells +list1 = list() +for value in ws.iter_rows(min_row = 1, max_row = 5, min_col = 1, max_col = 4, values_only = True): + list1.append(value) +# print(list1) + +# Display the values in a tabular method +for e1,e2,e3,e4 in list1: + '''unpacking of a tuple''' + # (print("{:<10}{:<35}{:<10}{:<5}".format(e1,e2,e3,e4))) + '''width of 1st column is 10, 2nd column is 35, 3rd column is 10, 4th column is 5''' + +# Write to a cell +ws['K1'] = 'Total Sales' + +# Add a new row +# new_row = ( +# 31, 'Cricket Premier League', 'PC', 2025, 'Sports', +# 'GameStudio', 2.60, 1.40, 3.80, 2.20, 10.0 +# ) +# ws.append(new_row) +# wb.save('VideoSales.xlsx') +# print(ws.max_row) + +# Delete a row +# ws.delete_rows(ws.max_row, 1) +# '''First parameter - row number from where the deletion starts. +# Second parameter - How many rows are to be deleted''' +# print(ws.max_row) +# wb.save('VideoSales.xlsx') +# print(ws.max_row) + +# ------------ Excel Formulas ---------------- + +# Average +ws['M1'] = 'Average Sales' +ws['M2'] = 'AVERAGE(K2:K31)' +wb.save('VideoSales.xlsx') + +# CountA +'''It counts the number of cells that are populated in a given range''' +# new_row = ( +# 29, 'Cricket Premier League', 'PC', ' ', 'Sports', +# 'GameStudio', 2.60, 1.40, 3.80, 2.20, 10.0 +# ) +# ws.append(new_row) +# wb.save('VideoSales.xlsx') +# print(ws.max_row) + +# ws['N1'] = 'Number of rows that have the value' +# ws['N2'] = '=COUNTA(D1:D32)' +# wb.save('VideoSales.xlsx') + +# Countif +'''This counts the number of cells that meet a criteria''' +# ws['01'] = 'Number of rows with Sports Genre' +# ws['02'] = 'COUNTIF(E2:E32, "Sports")' +# wb.save('VideoSales.xlsx') + +# Sumif +ws['M5'] = 'Total Sports Sales' +ws['M6'] = '=SUMIF(E2:E32, "Sports", K2:K32)' +'''First parameter - where should the criteria be checked + Second parameter - what is the criteria + Third parameter - what should be summed''' +wb.save('VideoSales.xlsx') From 4b96a47d0f0be62656f95fa1611832afe09aba49 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 22:59:39 +0530 Subject: [PATCH 023/132] Create file Exits error.py --- unit_3/file Exits error.py | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 unit_3/file Exits error.py diff --git a/unit_3/file Exits error.py b/unit_3/file Exits error.py new file mode 100644 index 0000000..54b4fe0 --- /dev/null +++ b/unit_3/file Exits error.py @@ -0,0 +1,5 @@ +def create_file(filepath): + open(filepath, 'x') # creates a file if it does not exists + print(f'{filepath} created successfully') + +create_file('new_file1.txt') # FileExistsError: [Errno 17] File exists: 'new_file1.txt' From aa9c66b52b21efdff2ab3efa164a3d043f714f82 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:00:28 +0530 Subject: [PATCH 024/132] Create file handling assignment.py --- unit_3/file handling assignment.py | 35 ++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 unit_3/file handling assignment.py diff --git a/unit_3/file handling assignment.py b/unit_3/file handling assignment.py new file mode 100644 index 0000000..d22bc67 --- /dev/null +++ b/unit_3/file handling assignment.py @@ -0,0 +1,35 @@ +# Assume that you have csv file of emp details that consist of name, empid, dept and sal. Read the file and compute the following values DA = 18% of sal, HRA = 2% of sal. +# Create an output file called as emp_sal.csv where empid, HRA, DA, Gross sal is written back. + +import csv + +# Input and output file names +input_file = "emp_details.csv" +output_file = "emp_sal.csv" + +with open(input_file, mode='r') as infile, open(output_file, mode='w', newline='') as outfile: + # Read CSV with semicolon delimiter + reader = csv.DictReader(infile, delimiter=';', skipinitialspace=True) + + # Output CSV header + fieldnames = ['Empid', 'HRA', 'DA', 'Gross'] + writer = csv.DictWriter(outfile, fieldnames=fieldnames) + writer.writeheader() + + for row in reader: + salary = float(row['Salary']) + + # Calculations + DA = 0.18 * salary + HRA = 0.02 * salary + Gross = salary + DA + HRA + + # Write to output CSV + writer.writerow({ + 'Empid': row['Empid'], + 'HRA': round(HRA, 2), + 'DA': round(DA, 2), + 'Gross': round(Gross, 2) + }) + +print("emp_sal.csv created successfully!") From 5970fd1912f8afec6efc583d1fd96a73626968ec Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:00:57 +0530 Subject: [PATCH 025/132] Create file handling dictreder.py --- unit_3/file handling dictreder.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 unit_3/file handling dictreder.py diff --git a/unit_3/file handling dictreder.py b/unit_3/file handling dictreder.py new file mode 100644 index 0000000..37d7869 --- /dev/null +++ b/unit_3/file handling dictreder.py @@ -0,0 +1,21 @@ +import csv + +with open('data1_8dec.csv','r') as f: + read_dict = csv.DictReader(f) + for r in read_dict: + print(r) +# print(type(r)) + +# with open('data2_8dec.csv','r') as f: +# read_dict = csv.DictReader(f, delimiter=';', skipinitialspace=True) +# for r in read_dict: +# print(r) + +with open('data2_8dec.csv','r') as f: + fnames = ['Name', 'Age', 'Profession'] + read_dict = csv.DictReader(f, fieldnames= fnames, delimiter=';', skipinitialspace=True) + for r in read_dict: + print(r) + +print(type(read_dict)) +print(type(r)) From efaffa0f787129b1f453f87a66b03ec550fca62b Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:01:39 +0530 Subject: [PATCH 026/132] Create file NOTEFOUND Error.py --- unit_3/file NOTEFOUND Error.py | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 unit_3/file NOTEFOUND Error.py diff --git a/unit_3/file NOTEFOUND Error.py b/unit_3/file NOTEFOUND Error.py new file mode 100644 index 0000000..724c4f0 --- /dev/null +++ b/unit_3/file NOTEFOUND Error.py @@ -0,0 +1,3 @@ +f = open('new.txt', 'r') # r opens the file if it exists in read mode +print('File opened') +'''FileNotFoundError: [Errno 2] No such file or directory: 'new.txt' ''' From 49418e5c439a84a10bc5b9d6c6f500a599c632b7 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:03:28 +0530 Subject: [PATCH 027/132] Delete userList.py --- userList.py | 40 ---------------------------------------- 1 file changed, 40 deletions(-) delete mode 100644 userList.py diff --git a/userList.py b/userList.py deleted file mode 100644 index 0541d55..0000000 --- a/userList.py +++ /dev/null @@ -1,40 +0,0 @@ -from collections import UserList - -# Create a custom list of the type UserList -class CustomList(UserList): - def addTwice(self, value): - self.data.append(value) - self.data.append(value) - def remtwice(self, pos): - self.data.pop(pos) - self.data.pop(pos) - -# Create an instance of CustomList -cl = CustomList([1,2,3,4,5,6,7]) -cl.append(8) -print(cl) # [1, 2, 3, 4, 5, 6, 7, 8] - -cl.extend([9,10]) -print(cl) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - -cl.insert(0,0) -print(cl) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - -cl.pop(3) -print(cl) # [0, 1, 2, 4, 5, 6, 7, 8, 9, 10] - -cl.remove(4) -print(cl) # [0, 1, 2, 5, 6, 7, 8, 9, 10] - -cl.reverse() -print(cl) # [10, 9, 8, 7, 6, 5, 2, 1, 0] - -cl.sort() -print(cl) # [0, 1, 2, 5, 6, 7, 8, 9, 10] - -#-------- Custom Methods -cl.addTwice(12) -print(cl) # [0, 1, 2, 5, 6, 7, 8, 9, 10, 12, 12] - -cl.remtwice(5) -print(cl) # [0, 1, 2, 5, 6, 9, 10, 12, 12] \ No newline at end of file From 339f6e54a06deaa0306dd495f3198da265a1c9a4 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:03:40 +0530 Subject: [PATCH 028/132] Delete decorators.py --- decorators.py | 68 --------------------------------------------------- 1 file changed, 68 deletions(-) delete mode 100644 decorators.py diff --git a/decorators.py b/decorators.py deleted file mode 100644 index e99c1cf..0000000 --- a/decorators.py +++ /dev/null @@ -1,68 +0,0 @@ -def div(x, y): - print(x / y) - -# ----------------- Wrapper Function ----------------- -def check(f): - def value(x, y): - if x < y: - x,y = y,x - return f(x,y) - return f(x,y) - return value -df = check(div) -df(10, 12) # 1.2 - -# ----------------- Syntatic Decorators ----------------- - -def split_val(f): - def val(): - func = f() - s_s = func.split() - return s_s - return val - -def upper_val(f): - def val(): - func = f() - u_v = func.upper() - return u_v - return val - -# Applying decorators on the normal function -@upper_val -def input_val(): - return 'This is Python program.' -print(input_val()) # Calling function - -@split_val -def input_val(): - return 'This is Python program.' -print(input_val()) # Calling function - -# Applying Single Decorator On Functions That can Take Parameters Or On Functions That Do Not take Parameters -# ----------------------------------------------------------------------------------------------------------- -# Wrapper Function -def dec(f): - def wrap(*args, **kwargs): - print(f'The positional arguments are {args}') - print(f'The keywords arguments are {kwargs}') - f(*args) - return wrap - -# Apply the decorator on a function that takes no parameter -@dec -def func_no(): - print('No Arguments passed') -print(func_no()) - -# Apply the decorator on a function that takes positional arguments -@dec -def f_pos(a,b,c): - print(f'The parameters are {a}, {b}, {c}') -print(f_pos(1,2,3)) - -# Apply the decorator on a function that takes Keyword arguments -@dec -def f_key(): - print('The function takes keyword arguments') -print(f_key(f_name = 'Harry', l_name = 'Potter', age = 11)) From 7721e9eebccb4e9aa20713e97497ea05d8e5220c Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:03:51 +0530 Subject: [PATCH 029/132] Delete nestedFunctions.py --- nestedFunctions.py | 31 ------------------------------- 1 file changed, 31 deletions(-) delete mode 100644 nestedFunctions.py diff --git a/nestedFunctions.py b/nestedFunctions.py deleted file mode 100644 index 967a4f1..0000000 --- a/nestedFunctions.py +++ /dev/null @@ -1,31 +0,0 @@ -import os -os.system('cls') - -#--------------- Scope of the variable in functions - -# def outer(): -# x = 10 -# print(f'Memory location of x is: {id(x)}') -# print(f'x in outer = {x}') -# def inner(): -# y = 10 + 5j -# print(f'Memory location of y in inner is: {id(y)}') -# print(f'y in inner = {y}') -# inner() -# print(f'Memory location of x is: {id(x)}') -# print(f'x in outer = {x}') -# outer() - -#---------------- Passing Arguments to Nested Functions - -def outer(n): - print(f'The value of n in outer is {n}') - def inner(): - m = int(input("Enter the value")) - print(f'The value of n in inner is {m}') - print(f'The value of n in inner is {n}') - inner() - print(f'The value of n in outer is {n}') -n = input("Enter the value") -(int)(n) -outer(n) \ No newline at end of file From b4893ab73b07544547dce006e0b6ec17117c6014 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:04:00 +0530 Subject: [PATCH 030/132] Delete expLearn1_2.py --- expLearn1_2.py | 20 -------------------- 1 file changed, 20 deletions(-) delete mode 100644 expLearn1_2.py diff --git a/expLearn1_2.py b/expLearn1_2.py deleted file mode 100644 index 92741e4..0000000 --- a/expLearn1_2.py +++ /dev/null @@ -1,20 +0,0 @@ -# Using a loop, collect 10 shopping items as input. -# Use a Counter to count occurrences and display the most common item. -# If there’s a tie, display all tied items. - -from collections import Counter - -ShoppingItems = [] - -for i in range(0,10): - items = input("Enter shopping item: ") - ShoppingItems.append(items) - -freq = Counter(ShoppingItems) -max_count = max(freq.values()) -print("Items which have occured more frequently: ") - -for item,count in freq.items(): - if count == max_count: - print(f"'{item} appears {count} times") - \ No newline at end of file From a7d10b42b52fb037c276a5f1d345f0aea162c549 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:04:09 +0530 Subject: [PATCH 031/132] Delete expLearn1_3.py --- expLearn1_3.py | 32 -------------------------------- 1 file changed, 32 deletions(-) delete mode 100644 expLearn1_3.py diff --git a/expLearn1_3.py b/expLearn1_3.py deleted file mode 100644 index 6dbbd16..0000000 --- a/expLearn1_3.py +++ /dev/null @@ -1,32 +0,0 @@ -# Read N words; use defaultdict(list) to group anagrams. Print only groups with size ≥ 3. - - - -from collections import defaultdict - -# Step 1: Create a defaultdict where each key maps to a list -anagrams = defaultdict(list) - -# Step 2: Read N (number of words) -n = int(input("Enter number of words: ")) - -# Step 3: Take N words as input and group them -for i in range(n): - word = input(f"Enter word {i + 1}: ").strip() - - # Step 3a: Sort the letters in the word to form a key - key = ''.join(sorted(word)) - - # Step 3b: Add the word to the corresponding group - anagrams[key].append(word) - -# Step 4: Print only groups that have 3 or more anagrams -print("\nAnagram groups with 3 or more words:\n") -found = False -for group in anagrams.values(): - if len(group) >= 3: - print(group) - found = True - -if not found: - print("No groups found with 3 or more anagrams.") From 5a3799989e80552beef14cbed37ebc12012d9199 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:04:19 +0530 Subject: [PATCH 032/132] Delete expLearn1_4.py --- expLearn1_4.py | 22 ---------------------- 1 file changed, 22 deletions(-) delete mode 100644 expLearn1_4.py diff --git a/expLearn1_4.py b/expLearn1_4.py deleted file mode 100644 index a354f6a..0000000 --- a/expLearn1_4.py +++ /dev/null @@ -1,22 +0,0 @@ -# Read N integers; build OrderedDict to keep first occurrence only. Print unique sequence preserving input order - -from collections import OrderedDict - -# Step 1: Create an empty OrderedDict -unique_numbers = OrderedDict() - -# Step 2: Read how many integers to input -n = int(input("Enter number of integers: ")) - -# Step 3: Read N integers one by one -for i in range(n): - num = int(input(f"Enter integer {i + 1}: ")) - - # Step 4: Add to OrderedDict only if not already present - if num not in unique_numbers: - unique_numbers[num] = True # Value doesn't matter, only key matters - -# Step 5: Print the unique sequence preserving the input order -print("\nUnique numbers (first occurrences only):") -for num in unique_numbers.keys(): - print(num, end=" ") From e6c555521f51a91117cbf1ab0b63bff0f364a06c Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:04:31 +0530 Subject: [PATCH 033/132] Delete methodResolutionOrder.py --- methodResolutionOrder.py | 34 ---------------------------------- 1 file changed, 34 deletions(-) delete mode 100644 methodResolutionOrder.py diff --git a/methodResolutionOrder.py b/methodResolutionOrder.py deleted file mode 100644 index 69abc91..0000000 --- a/methodResolutionOrder.py +++ /dev/null @@ -1,34 +0,0 @@ -# Base Class -class Root: - def do(self): - print("Root.do (completed)") - -# Inherited Classes -class A(Root): - def do(self): - print('A.do') - super().do() - -class B(A): - def do(self): - print("B.do") - super().do() - -class C(A): - def do(self): - print('C.do') - super().do() - -class D(B, C): - pass - -class E(C, B): - pass - -D().do() - -print('MRO of Class D:',[cls.__name__ for cls in D.mro()]) -print(D.__mro__) -print('MRO of Class E:',[cls.__name__ for cls in E.mro()]) -print(E.__mro__) - From b0fb15718d2f7fdab56a8652f514cd3fcd88a64b Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:04:41 +0530 Subject: [PATCH 034/132] Delete lambda functions.py --- lambda functions.py | 59 --------------------------------------------- 1 file changed, 59 deletions(-) delete mode 100644 lambda functions.py diff --git a/lambda functions.py b/lambda functions.py deleted file mode 100644 index f8e79dc..0000000 --- a/lambda functions.py +++ /dev/null @@ -1,59 +0,0 @@ -# Get the list of even numbers - -def is_even(n): - if n % 2 == 0: - return n - -l = list(filter(is_even, range(20))) -print(l) # [2, 4, 6, 8, 10, 12, 14, 16, 18] - -l = list(filter(lambda x: x%2 == 0, range(20))) -print(l) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] - -# Reduce() -# reduce(callable,iterable) -# callable - lambda/user-defined/built-in functions -# iterable - string/list/set/tuple/dictionary -# output - 1 output - -# Sum of numbers - -from functools import reduce -l = reduce(lambda a,b: a + b, [1,2,3,4,5,6,7,8,9,10]) -print(l) # 55 - -# Zip() -# zip(iterables...) - -l = list(zip([1,2,3,4,5],['a','b','c','d','e'],[0.0,1.1,2.2,3.3,4.4])) -print(l) # [(1, 'a', 0.0), (2, 'b', 1.1), (3, 'c', 2.2), (4, 'd', 3.3), (5, 'e', 4.4)] - -l = list(zip([1,2,3,4,5,6,7,8,9,10],['a','b','c','d','e'])) -print(l) # [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')] - -# Max() -# max(values) -# values = same type (except complex) -# output - largest or lexicographically largest value - -a = max('a','A','aa','AA') -print(a) # aa - -print(max([1,2,3,4],[1,2,4,5],[1,2,6,7],[1,2,6])) # [1, 2, 6, 7] - -# min(values) -# values - same type(except complex) -# output - smallest / lexicographically smallest - -print(min('a','A','aa','AA')) # A -print(min([1,2,3,4],[1,2,3],[1,2,3,5],[1,2,6])) # [1, 2, 3] - -# Operators - -import operator as o -print(o.add(10, 20)) # 30 -print(o.add(10, -20)) # -10 - -# sub(), truediv(), floordiv(), mul(), add(), mod(), gt(), ge(), le(), lt(), eq(), ne() -# or_, and_, not_, xor_ - From ee0e1a5c4a26617353305f75510db1151bd40d68 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:04:55 +0530 Subject: [PATCH 035/132] Delete listComprehensions.py --- listComprehensions.py | 20 -------------------- 1 file changed, 20 deletions(-) delete mode 100644 listComprehensions.py diff --git a/listComprehensions.py b/listComprehensions.py deleted file mode 100644 index 723ccf8..0000000 --- a/listComprehensions.py +++ /dev/null @@ -1,20 +0,0 @@ -# ---------------- Simple Comprehension ---------------- -l = [a for a in range(10)] -print(l) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - -l = [a*2 for a in range(10)] -print(l) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] - -# ---------------- Conditional Comprehension ---------------- -l = [a*2 for a in range(10) if( a%2 == 0)] -print(l) # [0, 4, 8, 12, 16] - -# ---------------- Nested Comprehension ---------------- -l = [a*b for a in range(1,5) for b in range(1,3)] -print(l) # [1, 2, 2, 4, 3, 6, 4, 8] - -# ---------------- Nested Conditional Comprehension ---------------- -l = [a*b for a in range(10) for b in range(5) if (a + b)%2 == 0] -print(l) # [0, 0, 0, 1, 3, 0, 4, 8, 3, 9, 0, 8, 16, 5, 15, 0, 12, 24, 7, 21, 0, 16, 32, 9, 27] - - From bdf650162d31608f5f12b51fd5b93d8e9be8f741 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:05:05 +0530 Subject: [PATCH 036/132] Delete setComprehension.py --- setComprehension.py | 27 --------------------------- 1 file changed, 27 deletions(-) delete mode 100644 setComprehension.py diff --git a/setComprehension.py b/setComprehension.py deleted file mode 100644 index 60e85cd..0000000 --- a/setComprehension.py +++ /dev/null @@ -1,27 +0,0 @@ -# ---------------- Simple Comprehension ---------------- -s = {a for a in range(10)} -print(s) # {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} - -s = {a*2 for a in range(10)} -print(s) # {0, 2, 4, 6, 8, 10, 12, 14, 16, 18} - -# ---------------- Conditional Comprehension ---------------- -s = {a*2 for a in range(10) if( a%2 == 0)} -print(s) # {0, 4, 8, 12, 16} - -s = {a+2 for a in range(10) if a%2 != 0} -print(s) # {3, 5, 7, 9, 11} - -# ---------------- Nested Comprehension ---------------- -s = {a*b for a in range(1,5) for b in range(1,3)} -print(s) # {1, 2, 3, 4, 6, 8} - -s = {(a,b) for a in [1,2,3,4,5] for b in ['a','b','c']} -print(s) # {(4, 'b'), (1, 'a'), (2, 'b'), (4, 'c'), (3, 'b'), (4, 'a'), (5, 'b'), (2, 'c'), (1, 'b'), (3, 'c'), (2, 'a'), (5, 'a'), (3, 'a'), (5, 'c'), (1, 'c')} - -# ---------------- Nested Conditional Comprehension ---------------- -s = {a*b for a in range(10) for b in range(5) if (a + b)%2 == 0} -print(s) # {0, 1, 32, 3, 4, 5, 7, 8, 9, 12, 15, 16, 21, 24, 27} - -s = {(a,b) for a in [1,2,3,4] for b in [4,5] if (a + b)%2 == 0} -print(s) # {(4, 4), (2, 4), (3, 5), (1, 5)} \ No newline at end of file From e27f91a617812efeec151da4c96b7c34b34469fb Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:05:16 +0530 Subject: [PATCH 037/132] Delete iterable.py --- iterable.py | 46 ---------------------------------------------- 1 file changed, 46 deletions(-) delete mode 100644 iterable.py diff --git a/iterable.py b/iterable.py deleted file mode 100644 index 413cfd1..0000000 --- a/iterable.py +++ /dev/null @@ -1,46 +0,0 @@ -l = [1,2,3,4,5] -l_iter = iter(l) -print(type(l),type(l_iter)) -print(next(l_iter), end = " ") -print(l_iter.__next__(), end = " ") -print(l_iter.__next__(), end = " ") -print(l_iter.__next__(), end = " ") -print(l_iter.__next__()) -# print(l_iter.__next__()) # ERROR: StopIteration - -# n = 123456789 -# n_iter = iter(n) # TypeError: 'int' object is not iterable - -str = 'Python Programming' -s_iter = iter(str) -print(type(str), type(s_iter)) - -t = (1,2,3,4,5) -t_iter = iter(t) - -d = {1:2, 3:4, 5:6, 7:8, 9:8} -d_iter = iter(d) -print(d_iter, ) # -print(d_iter) # -print(type(d), type(d_iter)) - -# -------------------- Infinite Cycle -------------------- - -import itertools as it -seq = it.chain(['A','B','C','D','E','F','G','H']) -seq_iter = iter(seq) -for _ in range(5): - print(next(seq_iter), end =" ") - -for _ in range(3): - print(next(seq)) - -# -------------------- Stop Iteration -------------------- - -s = {1,2,3,4,5} -s_iter = iter(s) -try: - while True: - print(next(s_iter)) -except StopIteration: - print("Completed") \ No newline at end of file From c90ff68582ab7d1f2c0ce986ddcc51b0d8cae31a Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:05:29 +0530 Subject: [PATCH 038/132] Delete functions.py --- functions.py | 80 ---------------------------------------------------- 1 file changed, 80 deletions(-) delete mode 100644 functions.py diff --git a/functions.py b/functions.py deleted file mode 100644 index c353827..0000000 --- a/functions.py +++ /dev/null @@ -1,80 +0,0 @@ -# --- Function Definition -def add(a, b): - return a+b - -# ---- Calling a function -print(add(10, 20)) # 30 -c = add(2, -3) -print(c) # -1 - -print(add(34.0, 32)) # 66.0 -print(add(32+34j, 32+56j)) # (64+90j) -print(add(32.34, 32+56j)) # (64.34+56j) -print(add('apple', 'banana')) # applebanana -print(add([1,2,3], ['banana'])) # [1, 2, 3, 'banana'] - -#------Keyword Arguments -print(add(b = 89, a = 60)) - -# ---- Default Arguments -def add(a = 10, b = 20): - return a + b -print(add()) #30 -print(add(-10)) #10 -print(add(b = -10)) #0 - -#---- Variable Length Arguments -def add(*n): - sum = 0 - for i in n: - sum += i - return sum - -print(add(10, 20, 30, 40, 50, 60)) - -#---- Variable with required/keyword/default -def add(*n, a, b): - sum = 0 - for i in n: - sum += i - sum += a - sum += b - return sum - -# print(add(10, 20, 30)) # TypeError: add() missing 2 required keyword-only arguments: 'a' and 'b' -print(add(a = 20, b = 30)) #50 - - -#----- Variable with default -def add(*n, a = 10, b = 40): - sum = 0 - for i in n: - sum += i - sum += a - sum += b - return sum - -print(add(10)) #60 -print(add(10, 20, 30)) #110 - -#------ Pass By Reference - -l = [1, 2, 3, 4] -print(id(l)) - -def list_mod(l): - l.append(20) - l.append(30) - print(l) #[1, 2, 3, 4, 20, 30] - return - -list_mod(l) -print(l, id(l)) - -def con(a, b): - a += b - return a -a = 'Hello' -b = 'World' -con(a, b) -print(id(a), id(b)) \ No newline at end of file From a0d85fcb4c01eacbfbcabe1890b558ea3a67367b Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:05:40 +0530 Subject: [PATCH 039/132] Delete exp_learn_2.py --- exp_learn_2.py | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 exp_learn_2.py diff --git a/exp_learn_2.py b/exp_learn_2.py deleted file mode 100644 index 75b39d3..0000000 --- a/exp_learn_2.py +++ /dev/null @@ -1,18 +0,0 @@ -a = ['SHannu', 'vAibhav', 'shridhar', 'heamaNNthU'] -l = [ch for word in a for ch in word if ch.isupper()] -print(l) - -# Create a list of all uppercase words from a given list. -words = ['HELLO', 'World', 'PYTHON', 'is', 'FUN'] -uppercase_words = [word for word in words if word.isupper()] -print(uppercase_words) # ['HELLO', 'PYTHON', 'FUN'] - -# Given a list of words create a list with words that starts with a vowel. -words = ['apple', 'banana', 'Orange', 'grape', 'umbrella', 'Egg'] -vowel_words = [word for word in words if word[0].lower() in 'aeiou'] -print(vowel_words) # ['apple', 'Orange', 'umbrella', 'Egg'] - -# Given a list of strings create a new list that contains the string and its length. -words = ['apple', 'banana', 'cherry', 'kiwi'] -word_lengths = [(word, len(word)) for word in words] -print(word_lengths) # [('apple', 5), ('banana', 6), ('cherry', 6), ('kiwi', 4)] From 1972b866ad746c86f8a27e4cb81b6f5ffbd74c73 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:05:50 +0530 Subject: [PATCH 040/132] Delete namedTuple.py --- namedTuple.py | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 namedTuple.py diff --git a/namedTuple.py b/namedTuple.py deleted file mode 100644 index 1c2ebc3..0000000 --- a/namedTuple.py +++ /dev/null @@ -1,10 +0,0 @@ -from collections import namedtuple - -Person = namedtuple('Person',{'name','age'}) - -p1 = Person(name = 'Alias', age = 10) -p2 = Person('Bob', 70) -p3 = Person(age = 11, name = 'Harry') - -print(p1) -print(p3.name) \ No newline at end of file From e52d7e4d414bb5c75795ce04d435f5e4bbf995e8 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:06:01 +0530 Subject: [PATCH 041/132] Delete recursiveFunction.py --- recursiveFunction.py | 41 ----------------------------------------- 1 file changed, 41 deletions(-) delete mode 100644 recursiveFunction.py diff --git a/recursiveFunction.py b/recursiveFunction.py deleted file mode 100644 index 979a14b..0000000 --- a/recursiveFunction.py +++ /dev/null @@ -1,41 +0,0 @@ -import os -os.system('cls') - -# def sum(n): -# if n == 0: -# return 0 -# else: -# return n + sum(n - 1) - -# n = int(input("Enter the number: ")) -# if n < 0: -# print(f"Sum of {n} values is not possible") -# else: -# print(f'Sum of n is {sum(n)}') - -# Recursion can cause stack overflow issues. -# Python has a built-in recurssion limit. - - -# ---------- Greatest Common Devisor ---------- - -# def gcdnm(a ,b): -# if b == 0: -# return a -# return gcdnm(b, a%b) -# a = int(input("Enter the first value")) -# b = int(input("Enter the second value")) - -# print(f'The GCD of {a}, {b} is {gcdnm(a,b)}') - -# ----------- Factorial ---------- - -def factorial(n): - if ((n == 0) or (n == 1)): - return 1 - else: - return n * factorial(n - 1) - -n = int(input("Enter the number")) -print(f'The factorial of {n} is:', factorial(n)) - From 43ecb46b834c5651455d5ae1b0bd000abdbfaabc Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:06:12 +0530 Subject: [PATCH 042/132] Delete sys.py --- sys.py | 36 ------------------------------------ 1 file changed, 36 deletions(-) delete mode 100644 sys.py diff --git a/sys.py b/sys.py deleted file mode 100644 index 533008a..0000000 --- a/sys.py +++ /dev/null @@ -1,36 +0,0 @@ -import sys - -# print('Enter the user name') -# u_name = sys.stdin.readline().rstrip('\n') #Equivalent to u_name = input("Enter the user name") - -# sys.stdout.write(u_name + '\n\n') #Equivalent to print(u_name); print('\n) - -# sys.stderr.write('This is error message') #Exception Handling - -#Get the size of variables -n = 1234567890 -lst1 = [1,2,3,4,5,6,7,8,9,0] -lst2 = ['1','2','3','4','5','6','7','8','9','0'] -set1 = {1,2,3,4,5,6,7,8,9,0} -set2 = {'1','2','3','4','5','6','7','8','9','0'} -tuple1 = (1,2,3,4,5,6,7,8,9,0) -tuple2 = ('1','2','3','4','5','6','7','8','9','0') -dict1 = {1:2, 2:3, 3:4, 4:5, 5:6, 6:7, 7:8, 8:9, 9:0} -dict2 = {'1':'2', '2':'3', '3':'4', '4':'5', '5':'6', '6':'7', '7':'8', '8':'9', '9':'0'} -dict3 = {} -f = 12345.67890 -c = 89 + 9j - -print(f'The size of {n} is {sys.getsizeof(n)} bytes') -print(f'The size of {lst1} is {sys.getsizeof(lst1)} bytes') -print(f'The size of {lst2} is {sys.getsizeof(lst2)} bytes') -print(f'The size of {set1} is {sys.getsizeof(set1)} bytes') -print(f'The size of {set2} is {sys.getsizeof(set2)} bytes') -print(f'The size of {tuple1} is {sys.getsizeof(tuple1)} bytes') -print(f'The size of {tuple2} is {sys.getsizeof(tuple2)} bytes') -print(f'The size of {dict1} is {sys.getsizeof(dict1)} bytes') -print(f'The size of {dict2} is {sys.getsizeof(dict2)} bytes') -print(f'The size of {f} is {sys.getsizeof(f)} bytes') -print(f'The size of {c} is {sys.getsizeof(c)} bytes') - -sys.exit(0) \ No newline at end of file From 3d47c5e5fd97119cb18e16dc150f727b5ddc6e20 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:06:22 +0530 Subject: [PATCH 043/132] Delete tempCodeRunnerFile.py --- tempCodeRunnerFile.py | 15 --------------- 1 file changed, 15 deletions(-) delete mode 100644 tempCodeRunnerFile.py diff --git a/tempCodeRunnerFile.py b/tempCodeRunnerFile.py deleted file mode 100644 index 93e8e7a..0000000 --- a/tempCodeRunnerFile.py +++ /dev/null @@ -1,15 +0,0 @@ -class Dog: -# def __init__(self, name, breed, age): -# self.name = name -# self.breed = breed -# self.age = age - -# def barks(self): -# print(f'{self.name} says Woof') - -# def sleep(self): -# print(f'{self.name} is sleeping now Zzz') - -# d1 = Dog('Tommy', 'German Shepherd',12) -# d1.barks() -# d1.sleep() \ No newline at end of file From 8344ef944a5d7d3dbb08bac70f74ab9c092345d4 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:06:32 +0530 Subject: [PATCH 044/132] Delete userDictionary.py --- userDictionary.py | 15 --------------- 1 file changed, 15 deletions(-) delete mode 100644 userDictionary.py diff --git a/userDictionary.py b/userDictionary.py deleted file mode 100644 index a361b52..0000000 --- a/userDictionary.py +++ /dev/null @@ -1,15 +0,0 @@ -from collections import UserDict - -# Creation of user Dictionary - -class MyUserDict(UserDict): - def get_keys(self): - return {keys.upper() for keys in self.keys()} - -# Create an instance of my userDict -cd = MyUserDict({'apple':10, 'banana':20, 'cherry':30}) -print(cd) -print(type(cd)) -print(cd.get_keys()) -cd.keys() - From e199a71dd848746507c93c6a66e69d00da5bcf79 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:06:43 +0530 Subject: [PATCH 045/132] Delete dictionaryComprehension.py --- dictionaryComprehension.py | 20 -------------------- 1 file changed, 20 deletions(-) delete mode 100644 dictionaryComprehension.py diff --git a/dictionaryComprehension.py b/dictionaryComprehension.py deleted file mode 100644 index 627e493..0000000 --- a/dictionaryComprehension.py +++ /dev/null @@ -1,20 +0,0 @@ -# Syntax {key_exp : value_exp for item in iterable} - -# ---------------- Simple Comprehension ---------------- -even_squares = {x: x**2 for x in range(10)} -print(even_squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} - -d = {a: a+10 for a in range(5)} -print(d) # {0: 10, 1: 11, 2: 12, 3: 13, 4: 14} - -# ---------------- Conditional Comprehension ---------------- -d = {a: a**3 for a in range(10) if (a**3 % 4) == 0} -print(d) # {0: 0, 2: 8, 4: 64, 6: 216, 8: 512} - -# ---------------- Nested Comprehension ---------------- -d = {a: {b: a+b for b in 'ABC'} for a in 'ABC'} -print(d) # {'A': {'A': 'AA', 'B': 'AB', 'C': 'AC'}, 'B': {'A': 'BA', 'B': 'BB', 'C': 'BC'}, 'C': {'A': 'CA', 'B': 'CB', 'C': 'CC'}} - -# ---------------- Nested Conditional Comprehension ---------------- -d = {x: {y: 'EVEN' if y%2 == 0 else 'ODD' for y in range(1,5)} for x in range(1,3)} -print(d) # {1: {1: 'ODD', 2: 'EVEN', 3: 'ODD', 4: 'EVEN'}, 2: {1: 'ODD', 2: 'EVEN', 3: 'ODD', 4: 'EVEN'}} From 069df565016e15f72f0af9b29328923a3e465397 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:06:54 +0530 Subject: [PATCH 046/132] Delete datetime.py --- datetime.py | 22 ---------------------- 1 file changed, 22 deletions(-) delete mode 100644 datetime.py diff --git a/datetime.py b/datetime.py deleted file mode 100644 index 1bb77ea..0000000 --- a/datetime.py +++ /dev/null @@ -1,22 +0,0 @@ -from datetime import datetime, time -import sys - -print(f'The current day is {datetime.now().strftime("%w")}') - - -#%d - day of the month -#%j - day of the year(3 digits 1 to 365) -#%b %B - month name ( abbr, full) -#%m - month of the yaer -#%y %Y - year (2 digits, 4 digits) -#%H %I - hour (24 hour, 12 hour) - -#Accessing system Information -# a. Version - -print(f'The python version is {sys.version}') - -# b. Operating System - -print(f'The Operation system is {sys.platform}') - From ac20fc7049d2a580b5c9674941f07a6a28ac6e73 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 6 Mar 2026 23:07:06 +0530 Subject: [PATCH 047/132] Delete collectionsCounter.py --- collectionsCounter.py | 29 ----------------------------- 1 file changed, 29 deletions(-) delete mode 100644 collectionsCounter.py diff --git a/collectionsCounter.py b/collectionsCounter.py deleted file mode 100644 index 4e4ccdd..0000000 --- a/collectionsCounter.py +++ /dev/null @@ -1,29 +0,0 @@ -from collections import Counter -from collections import deque -#counter - counts the occurrences in an iterable or sequence - -l = [1,2,3,4,1,2,4] -print(Counter(l)) # Counter({1: 2, 2: 2, 4: 2, 3: 1}) - -s = 'This is a statement' -print(Counter(s)) # Counter({'s': 3, ' ': 3, 't': 3, 'i': 2, 'a': 2, 'e': 2, 'T': 1, 'h': 1, 'm': 1, 'n': 1}) - -#Deque -d = deque([10,20,30,40,50]) -type(d) - -#Instertion in rear - -d.append(60) -print(d) # deque([10, 20, 30, 40, 50, 60]) - -#Insert at front -d.appendleft(70) - -#Deletion at rear -d.pop() -print(d) # deque([70, 10, 20, 30, 40, 50]) - -#Deletion at front -d.popleft() -print(d) # deque([10, 20, 30, 40, 50]) \ No newline at end of file From a947cef8f680e38183ead187658abf8b40508fb6 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:34:10 +0530 Subject: [PATCH 048/132] Create file not found not error.py --- unit_3/file not found not error.py | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 unit_3/file not found not error.py diff --git a/unit_3/file not found not error.py b/unit_3/file not found not error.py new file mode 100644 index 0000000..724c4f0 --- /dev/null +++ b/unit_3/file not found not error.py @@ -0,0 +1,3 @@ +f = open('new.txt', 'r') # r opens the file if it exists in read mode +print('File opened') +'''FileNotFoundError: [Errno 2] No such file or directory: 'new.txt' ''' From e5988aa9b9d82e455779a3cbcbfd93d4f335c199 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:34:35 +0530 Subject: [PATCH 049/132] Create file writer.py --- unit_3/file writer.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 unit_3/file writer.py diff --git a/unit_3/file writer.py b/unit_3/file writer.py new file mode 100644 index 0000000..a2ea7e4 --- /dev/null +++ b/unit_3/file writer.py @@ -0,0 +1,19 @@ +# Write the CSV Files - To write into CSV it has to be List of Lists + +import csv + +data = [ + ['Name', 'Age', 'City'], + ['Abbot', 11, 'BLR'], + ['Shannu', 30, 'HNR'], + ['Bob', 40, 'MLR'] +] + +with open('output_data.csv','w') as f: + write = csv.writer(f) + write.writerows(data) + +with open('output_data.csv','a') as f: + write = csv.writer(f) + write.writerow(['Dean', 11, 'Manchester']) + write.writerow(['eDGAR', 20, 'PARIS']) From 9a784f8e06ea829fc8c72bc5f77c58690373a1f9 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:34:58 +0530 Subject: [PATCH 050/132] Create fileHandling.py --- unit_3/fileHandling.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 unit_3/fileHandling.py diff --git a/unit_3/fileHandling.py b/unit_3/fileHandling.py new file mode 100644 index 0000000..9cb9dd7 --- /dev/null +++ b/unit_3/fileHandling.py @@ -0,0 +1,13 @@ +import csv + +# Read CSV files +with open('data.csv','r') as f: + read=csv.reader(f) + for r in read: + print(r) + + +with open('data1_8dec.csv','r') as f: + read=csv.reader(f, delimiter= ';', skipinitialspace= True) + for r in read: + print(r) From be9981afef5481190b702f1cf5045cf7c46b23b8 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:35:21 +0530 Subject: [PATCH 051/132] Create import this.py --- unit_3/import this.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 unit_3/import this.py diff --git a/unit_3/import this.py b/unit_3/import this.py new file mode 100644 index 0000000..86501a8 --- /dev/null +++ b/unit_3/import this.py @@ -0,0 +1,23 @@ +import this + +'''The Zen of Python, by Tim Peters + +Beautiful is better than ugly. +Explicit is better than implicit. +Simple is better than complex. +Complex is better than complicated. +Flat is better than nested. +Sparse is better than dense. +Readability counts. +Special cases aren't special enough to break the rules. +Although practicality beats purity. +Errors should never pass silently. +Unless explicitly silenced. +In the face of ambiguity, refuse the temptation to guess. +There should be one-- and preferably only one --obvious way to do it. +Although that way may not be obvious at first unless you're Dutch. +Now is better than never. +Although never is often better than *right* now. +If the implementation is hard to explain, it's a bad idea. +If the implementation is easy to explain, it may be a good idea. +Namespaces are one honking great idea -- let's do more of those!''' From 69e3c70708c569c45f609f5ffcfd0be892f65ec6 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:35:43 +0530 Subject: [PATCH 052/132] Create IO error.py --- unit_3/IO error.py | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 unit_3/IO error.py diff --git a/unit_3/IO error.py b/unit_3/IO error.py new file mode 100644 index 0000000..5149474 --- /dev/null +++ b/unit_3/IO error.py @@ -0,0 +1,5 @@ +try: + f = open('new.txt', 'r') + print('File Opened') +except IOError as e: + print(f'IOError: {e}') From 4bfdf892409f36b3e8b6c44864186c965457441f Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:36:20 +0530 Subject: [PATCH 053/132] Create Json file handling.py --- unit_3/Json file handling.py | 47 ++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 unit_3/Json file handling.py diff --git a/unit_3/Json file handling.py b/unit_3/Json file handling.py new file mode 100644 index 0000000..2c7c30c --- /dev/null +++ b/unit_3/Json file handling.py @@ -0,0 +1,47 @@ +import json as j + +p = '{"name":"Alpha","age":30}' +p_dict = j.loads(p) +print(type(p), type(p_dict)) + +# with open('Json file1.json','r') as f: +# p_json = j.load(f) +# print(type(p_json)) +# print(p_json) + +# with open('Json file2.json','r') as f: +# p2_json = j.load(f) +# print(type(p2_json)) +# print(p2_json) + +# print(p2_json[0]["name"]) +# for r in p2_json: + # print(r['name']) + +print("Json file3") +with open('Json file3.json','r') as f: + p3_json = j.load(f) + print(type(p3_json)) + print(p3_json) + print(p3_json['alpha']['city']) + for r in p3_json: + print(f'Name : {r}') + print(f"Age: {p3_json[r]['age']}") + print(f"City: {p3_json[r]['city']}") + +# ----------- Writing the JSON objects------------ + +n_dict = {'name':'Delta','age':25} +n_json = j.dumps(n_dict) +print(type(n_dict),type(n_json)) +print(n_dict) +print(n_json) + +with open('Json file4.json','w') as f: + j.dump(n_dict, f) + +with open('Json file4.json','a') as f: + j.dump(n_dict,f) + +with open('Json file4.txt','w') as f: + j.dump(n_dict, f) From a1e00e3e57b545a3adbcd915e48ae8261a139d83 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:37:05 +0530 Subject: [PATCH 054/132] Create Keyboardinterrput Error.py --- unit_3/Keyboardinterrput Error.py | 1 + 1 file changed, 1 insertion(+) create mode 100644 unit_3/Keyboardinterrput Error.py diff --git a/unit_3/Keyboardinterrput Error.py b/unit_3/Keyboardinterrput Error.py new file mode 100644 index 0000000..5088305 --- /dev/null +++ b/unit_3/Keyboardinterrput Error.py @@ -0,0 +1 @@ +name = input("Enter the value") From ac6e3b06e8b8bec83e17bdd7851047e2129d37ae Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:37:38 +0530 Subject: [PATCH 055/132] Create KeyError.py --- unit_3/KeyError.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 unit_3/KeyError.py diff --git a/unit_3/KeyError.py b/unit_3/KeyError.py new file mode 100644 index 0000000..5a83a43 --- /dev/null +++ b/unit_3/KeyError.py @@ -0,0 +1,10 @@ +# d = {'name' : 'Alpha', 'age':20, 'city':'Bengaluru'} +# print(d['address']) # KeyError: 'address' + + +# LookupError +try: + d = {'name' : 'Alpha', 'age':20, 'city':'Bengaluru'} + d['address'] +except LookupError as e: + print(f'LookupError: {e}') From ef66f3dc5f3753975eca62273b65d8e3345df035 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:38:46 +0530 Subject: [PATCH 056/132] Create Multiple Exception Handling.py --- unit_3/Multiple Exception Handling.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 unit_3/Multiple Exception Handling.py diff --git a/unit_3/Multiple Exception Handling.py b/unit_3/Multiple Exception Handling.py new file mode 100644 index 0000000..c45b53b --- /dev/null +++ b/unit_3/Multiple Exception Handling.py @@ -0,0 +1,9 @@ +try: + l = [0, 2, 4, 6, 8, 10] + i1 = int(input("Enter the first index")) + i2 = int(input("Enter the second index")) + print(l[i1]/l[i2]) +except IndexError as e: + print(f'IndexError: {e}. Check the index number') +except ZeroDivisionError as e: + print(f'ZeroDivisionError: {e}. The index is pointing to a 0 value') From 9ac0b25ff7bc27d865111aec018afa52d8e92270 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:39:15 +0530 Subject: [PATCH 057/132] Create Name Error.py --- unit_3/Name Error.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 unit_3/Name Error.py diff --git a/unit_3/Name Error.py b/unit_3/Name Error.py new file mode 100644 index 0000000..3ed695e --- /dev/null +++ b/unit_3/Name Error.py @@ -0,0 +1,8 @@ +# x = 10 +# z = x + y # NameError: name 'y' is not defined +# print(z) + +x = '10' +y = 10 +z = x+y # TypeError: can only concatenate str (not "int") to str +print(z) From 2fd6ae5d557258d0f00515ad4380993ecae7b827 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:42:05 +0530 Subject: [PATCH 058/132] Add files via upload --- Assertion Error.py | 7 +++ AttributeError.py | 12 ++++ CSV_data_frame.py | 37 ++++++++++++ Creating a new worksheet.py | 25 +++++++++ Exception Handling finally.py | 10 ++++ Exception Handling.py | 28 +++++++++ File Exists Error.py | 5 ++ File NotFound Error.py | 3 + File handling Assignment.py | 36 ++++++++++++ FileHandling(CSV).py | 13 +++++ IO Error.py | 5 ++ Json file handling.py | 47 ++++++++++++++++ KeyError.py | 10 ++++ KeyboardInterrupt Error.py | 1 + Multiple Exception Handling.py | 9 +++ Name Error.py | 8 +++ file excel handling.py | 100 +++++++++++++++++++++++++++++++++ file handling dictreader.py | 21 +++++++ import this.py | 23 ++++++++ 19 files changed, 400 insertions(+) create mode 100644 Assertion Error.py create mode 100644 AttributeError.py create mode 100644 CSV_data_frame.py create mode 100644 Creating a new worksheet.py create mode 100644 Exception Handling finally.py create mode 100644 Exception Handling.py create mode 100644 File Exists Error.py create mode 100644 File NotFound Error.py create mode 100644 File handling Assignment.py create mode 100644 FileHandling(CSV).py create mode 100644 IO Error.py create mode 100644 Json file handling.py create mode 100644 KeyError.py create mode 100644 KeyboardInterrupt Error.py create mode 100644 Multiple Exception Handling.py create mode 100644 Name Error.py create mode 100644 file excel handling.py create mode 100644 file handling dictreader.py create mode 100644 import this.py diff --git a/Assertion Error.py b/Assertion Error.py new file mode 100644 index 0000000..399606a --- /dev/null +++ b/Assertion Error.py @@ -0,0 +1,7 @@ +def division(a,b): + assert b != 0 + return a/b + +print(division(10,2)) +print(division(10,0.5)) +print(division(10,0)) # AssertionError \ No newline at end of file diff --git a/AttributeError.py b/AttributeError.py new file mode 100644 index 0000000..325623f --- /dev/null +++ b/AttributeError.py @@ -0,0 +1,12 @@ +# s = "Hello to Errors" +# s.reverse() + +class Person: + def __init__(self, name, age): + self.name = name + self.age = age + def greet(self): + print(f'Hello, My name is {self.name})') + +p = Person('Ironman', 40) +p.city # AttributeError: 'Person' object has no attribute 'city' \ No newline at end of file diff --git a/CSV_data_frame.py b/CSV_data_frame.py new file mode 100644 index 0000000..852cec4 --- /dev/null +++ b/CSV_data_frame.py @@ -0,0 +1,37 @@ +import pandas as pd + +sd = pd.read_csv('sales_demo.csv') +pr = pd.read_csv('products_demo.csv') + +print(type(sd), type(pr)) + +print(sd.shape) +print(pr.shape) + +print(sd.columns) + +print(pr['ProductID'].nunique()) +print(len(pr)) + +df = pd.merge(sd, pr, on = "ProductID", how = "inner") +print(df.shape) + +m_left = pd.merge(sd, pr, on = "ProductID", how = "left") +m_left1 = pd.merge(pr, sd, on = "ProductID", how = "left") + +print(m_left.shape, m_left1.shape) + +m_right = pd.merge(sd, pr, on = "ProductID", how = "right") +m_right1 = pd.merge(pr, sd, on = "ProductID", how = "right") + +print(m_right.shape, m_right1.shape) +m_outer = pd.merge(sd, pr, on = "ProductID", how = "outer") +m_outer1 = pd.merge(pr, sd, on = "ProductID", how = "outer") +print(m_outer.shape, m_outer1.shape) +print(m_outer, m_outer1) + +''' Inner join - common records from both data frames + Outer join - all reccords from both data frames + Left join - all records of left data frames + Right join - all records of right data frames''' + diff --git a/Creating a new worksheet.py b/Creating a new worksheet.py new file mode 100644 index 0000000..54aa14a --- /dev/null +++ b/Creating a new worksheet.py @@ -0,0 +1,25 @@ +import openpyxl as op + +wb = op.load_workbook('.\VideoSales.xlsx') +ws = wb.active +# ws = wb['SalesData'] +# wb.create_sheet('New Sheet') +# wb.save('VideoSales.xlsx') +# print(wb.sheetnames) + +# --------- Title of active sheet ------------- +print(ws.title) + +# --------- Rename a sheet ---------------- +# ws = wb['New Sheet1'] +# print(ws.title) +ws.title = 'A New Sheet' +# wb.save('VideoSales.xlsx') +# print(wb.sheetnames) +print(wb.sheetnames) + +# Duplicate a worksheet +new_ws = wb.copy_worksheet(wb['A New Sheet1']) +new_ws.title = 'A New Sheet' +wb.save('VideoSales.xlsx') +print(wb.sheetnames) \ No newline at end of file diff --git a/Exception Handling finally.py b/Exception Handling finally.py new file mode 100644 index 0000000..cfe014b --- /dev/null +++ b/Exception Handling finally.py @@ -0,0 +1,10 @@ +n = int(input("Enter the numerator: ")) +try: + d = int(input("Enter the denominator: ")) + print(n/d) +except: + print("Error: Denominator cannot be a zero") +finally: + print("Division may have occurred") + ''' finally block is executed if the exception is identifed and handled + finally block is executed if the exception does not occur also''' \ No newline at end of file diff --git a/Exception Handling.py b/Exception Handling.py new file mode 100644 index 0000000..e4d3069 --- /dev/null +++ b/Exception Handling.py @@ -0,0 +1,28 @@ +# Try and Except block + +n = int(input("Enter the numerator: ")) +try: + d = int(input("Enter the denominator: ")) + print(n/d) +except ZeroDivisionError as e: + print(f'ZeroDivisionError: {e}') + +n = int(input("Enter the numerator: ")) +d = int(input("Enter the denominator: ")) +print(n/d) + + +# Try except and else block + +try: + n = int(input("Enter a number: ")) + assert n%2 == 0 +except: + print("Not an even number") +else: + print(n/4) + + +''' Try - code where the error might occur + Except - what should be done if the error occurs + Else - what else should be done if the error does not occur''' \ No newline at end of file diff --git a/File Exists Error.py b/File Exists Error.py new file mode 100644 index 0000000..fb0aee2 --- /dev/null +++ b/File Exists Error.py @@ -0,0 +1,5 @@ +def create_file(filepath): + open(filepath, 'x') # creates a file if it does not exists + print(f'{filepath} created successfully') + +create_file('new_file1.txt') # FileExistsError: [Errno 17] File exists: 'new_file1.txt' \ No newline at end of file diff --git a/File NotFound Error.py b/File NotFound Error.py new file mode 100644 index 0000000..6cad074 --- /dev/null +++ b/File NotFound Error.py @@ -0,0 +1,3 @@ +f = open('new.txt', 'r') # r opens the file if it exists in read mode +print('File opened') +'''FileNotFoundError: [Errno 2] No such file or directory: 'new.txt' ''' \ No newline at end of file diff --git a/File handling Assignment.py b/File handling Assignment.py new file mode 100644 index 0000000..0fdbf78 --- /dev/null +++ b/File handling Assignment.py @@ -0,0 +1,36 @@ +# Assume that you have csv file of emp details that consist of name, empid, dept and sal. Read the file and compute the following values DA = 18% of sal, HRA = 2% of sal. +# Create an output file called as emp_sal.csv where empid, HRA, DA, Gross sal is written back. + +import csv + +# Input and output file names +input_file = "emp_details.csv" +output_file = "emp_sal.csv" + +with open(input_file, mode='r') as infile, open(output_file, mode='w', newline='') as outfile: + # Read CSV with semicolon delimiter + reader = csv.DictReader(infile, delimiter=';', skipinitialspace=True) + + # Output CSV header + fieldnames = ['Empid', 'HRA', 'DA', 'Gross'] + writer = csv.DictWriter(outfile, fieldnames=fieldnames) + writer.writeheader() + + for row in reader: + salary = float(row['Salary']) + + # Calculations + DA = 0.18 * salary + HRA = 0.02 * salary + Gross = salary + DA + HRA + + # Write to output CSV + writer.writerow({ + 'Empid': row['Empid'], + 'HRA': round(HRA, 2), + 'DA': round(DA, 2), + 'Gross': round(Gross, 2) + }) + +print("emp_sal.csv created successfully!") + diff --git a/FileHandling(CSV).py b/FileHandling(CSV).py new file mode 100644 index 0000000..ee024a0 --- /dev/null +++ b/FileHandling(CSV).py @@ -0,0 +1,13 @@ +import csv + +# Read CSV files +with open('data.csv','r') as f: + read=csv.reader(f) + for r in read: + print(r) + + +with open('data1_8dec.csv','r') as f: + read=csv.reader(f, delimiter= ';', skipinitialspace= True) + for r in read: + print(r) \ No newline at end of file diff --git a/IO Error.py b/IO Error.py new file mode 100644 index 0000000..bf25091 --- /dev/null +++ b/IO Error.py @@ -0,0 +1,5 @@ +try: + f = open('new.txt', 'r') + print('File Opened') +except IOError as e: + print(f'IOError: {e}') \ No newline at end of file diff --git a/Json file handling.py b/Json file handling.py new file mode 100644 index 0000000..73187b4 --- /dev/null +++ b/Json file handling.py @@ -0,0 +1,47 @@ +import json as j + +p = '{"name":"Alpha","age":30}' +p_dict = j.loads(p) +print(type(p), type(p_dict)) + +# with open('Json file1.json','r') as f: +# p_json = j.load(f) +# print(type(p_json)) +# print(p_json) + +# with open('Json file2.json','r') as f: +# p2_json = j.load(f) +# print(type(p2_json)) +# print(p2_json) + +# print(p2_json[0]["name"]) +# for r in p2_json: + # print(r['name']) + +print("Json file3") +with open('Json file3.json','r') as f: + p3_json = j.load(f) + print(type(p3_json)) + print(p3_json) + print(p3_json['alpha']['city']) + for r in p3_json: + print(f'Name : {r}') + print(f"Age: {p3_json[r]['age']}") + print(f"City: {p3_json[r]['city']}") + +# ----------- Writing the JSON objects------------ + +n_dict = {'name':'Delta','age':25} +n_json = j.dumps(n_dict) +print(type(n_dict),type(n_json)) +print(n_dict) +print(n_json) + +with open('Json file4.json','w') as f: + j.dump(n_dict, f) + +with open('Json file4.json','a') as f: + j.dump(n_dict,f) + +with open('Json file4.txt','w') as f: + j.dump(n_dict, f) \ No newline at end of file diff --git a/KeyError.py b/KeyError.py new file mode 100644 index 0000000..7726824 --- /dev/null +++ b/KeyError.py @@ -0,0 +1,10 @@ +# d = {'name' : 'Alpha', 'age':20, 'city':'Bengaluru'} +# print(d['address']) # KeyError: 'address' + + +# LookupError +try: + d = {'name' : 'Alpha', 'age':20, 'city':'Bengaluru'} + d['address'] +except LookupError as e: + print(f'LookupError: {e}') diff --git a/KeyboardInterrupt Error.py b/KeyboardInterrupt Error.py new file mode 100644 index 0000000..80d788c --- /dev/null +++ b/KeyboardInterrupt Error.py @@ -0,0 +1 @@ +name = input("Enter the value") \ No newline at end of file diff --git a/Multiple Exception Handling.py b/Multiple Exception Handling.py new file mode 100644 index 0000000..3cec7e3 --- /dev/null +++ b/Multiple Exception Handling.py @@ -0,0 +1,9 @@ +try: + l = [0, 2, 4, 6, 8, 10] + i1 = int(input("Enter the first index")) + i2 = int(input("Enter the second index")) + print(l[i1]/l[i2]) +except IndexError as e: + print(f'IndexError: {e}. Check the index number') +except ZeroDivisionError as e: + print(f'ZeroDivisionError: {e}. The index is pointing to a 0 value') diff --git a/Name Error.py b/Name Error.py new file mode 100644 index 0000000..7d7a5b6 --- /dev/null +++ b/Name Error.py @@ -0,0 +1,8 @@ +# x = 10 +# z = x + y # NameError: name 'y' is not defined +# print(z) + +x = '10' +y = 10 +z = x+y # TypeError: can only concatenate str (not "int") to str +print(z) \ No newline at end of file diff --git a/file excel handling.py b/file excel handling.py new file mode 100644 index 0000000..eda118a --- /dev/null +++ b/file excel handling.py @@ -0,0 +1,100 @@ +import openpyxl as op +# load the workbook +wb = op.load_workbook('.\VideoSales.xlsx') +# print(type(wb)) # + +# print(wb) # + +# Call the active worksheet +ws = wb.active +# print(type(ws)) + +# Call the sheet by it's name +ws = wb['SalesData'] +# print(ws) # + +# Count the number of rows and columns that are filled in the worksheet +# print(f'Total number of rows is {ws.max_row} and total number of columns is {ws.max_column}') + +# Read the data from a cell +# print(f"The value stored in cell D5 is: {ws['D5'].value}") + +# Read data from multiple cells +values = [ + ws.cell(row = 1, column = i).value + for i in range(1, ws.max_column + 1) +] +# print(values) + +data = [ + ws.cell(row = 1, column = i).value + for i in range(1, ws.max_column + 1) +] +# print(values) + +# Reading data from a range of cells +list1 = list() +for value in ws.iter_rows(min_row = 1, max_row = 5, min_col = 1, max_col = 4, values_only = True): + list1.append(value) +# print(list1) + +# Display the values in a tabular method +for e1,e2,e3,e4 in list1: + '''unpacking of a tuple''' + # (print("{:<10}{:<35}{:<10}{:<5}".format(e1,e2,e3,e4))) + '''width of 1st column is 10, 2nd column is 35, 3rd column is 10, 4th column is 5''' + +# Write to a cell +ws['K1'] = 'Total Sales' + +# Add a new row +# new_row = ( +# 31, 'Cricket Premier League', 'PC', 2025, 'Sports', +# 'GameStudio', 2.60, 1.40, 3.80, 2.20, 10.0 +# ) +# ws.append(new_row) +# wb.save('VideoSales.xlsx') +# print(ws.max_row) + +# Delete a row +# ws.delete_rows(ws.max_row, 1) +# '''First parameter - row number from where the deletion starts. +# Second parameter - How many rows are to be deleted''' +# print(ws.max_row) +# wb.save('VideoSales.xlsx') +# print(ws.max_row) + +# ------------ Excel Formulas ---------------- + +# Average +ws['M1'] = 'Average Sales' +ws['M2'] = 'AVERAGE(K2:K31)' +wb.save('VideoSales.xlsx') + +# CountA +'''It counts the number of cells that are populated in a given range''' +# new_row = ( +# 29, 'Cricket Premier League', 'PC', ' ', 'Sports', +# 'GameStudio', 2.60, 1.40, 3.80, 2.20, 10.0 +# ) +# ws.append(new_row) +# wb.save('VideoSales.xlsx') +# print(ws.max_row) + +# ws['N1'] = 'Number of rows that have the value' +# ws['N2'] = '=COUNTA(D1:D32)' +# wb.save('VideoSales.xlsx') + +# Countif +'''This counts the number of cells that meet a criteria''' +# ws['01'] = 'Number of rows with Sports Genre' +# ws['02'] = 'COUNTIF(E2:E32, "Sports")' +# wb.save('VideoSales.xlsx') + +# Sumif +ws['M5'] = 'Total Sports Sales' +ws['M6'] = '=SUMIF(E2:E32, "Sports", K2:K32)' +'''First parameter - where should the criteria be checked + Second parameter - what is the criteria + Third parameter - what should be summed''' +wb.save('VideoSales.xlsx') diff --git a/file handling dictreader.py b/file handling dictreader.py new file mode 100644 index 0000000..b91c052 --- /dev/null +++ b/file handling dictreader.py @@ -0,0 +1,21 @@ +import csv + +with open('data1_8dec.csv','r') as f: + read_dict = csv.DictReader(f) + for r in read_dict: + print(r) +# print(type(r)) + +# with open('data2_8dec.csv','r') as f: +# read_dict = csv.DictReader(f, delimiter=';', skipinitialspace=True) +# for r in read_dict: +# print(r) + +with open('data2_8dec.csv','r') as f: + fnames = ['Name', 'Age', 'Profession'] + read_dict = csv.DictReader(f, fieldnames= fnames, delimiter=';', skipinitialspace=True) + for r in read_dict: + print(r) + +print(type(read_dict)) +print(type(r)) \ No newline at end of file diff --git a/import this.py b/import this.py new file mode 100644 index 0000000..9c3b721 --- /dev/null +++ b/import this.py @@ -0,0 +1,23 @@ +import this + +'''The Zen of Python, by Tim Peters + +Beautiful is better than ugly. +Explicit is better than implicit. +Simple is better than complex. +Complex is better than complicated. +Flat is better than nested. +Sparse is better than dense. +Readability counts. +Special cases aren't special enough to break the rules. +Although practicality beats purity. +Errors should never pass silently. +Unless explicitly silenced. +In the face of ambiguity, refuse the temptation to guess. +There should be one-- and preferably only one --obvious way to do it. +Although that way may not be obvious at first unless you're Dutch. +Now is better than never. +Although never is often better than *right* now. +If the implementation is hard to explain, it's a bad idea. +If the implementation is easy to explain, it may be a good idea. +Namespaces are one honking great idea -- let's do more of those!''' \ No newline at end of file From 98cb6407aa177e309e41ba55d79d1f17f34a5c17 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:42:50 +0530 Subject: [PATCH 059/132] Delete Assertion Error.py --- Assertion Error.py | 7 ------- 1 file changed, 7 deletions(-) delete mode 100644 Assertion Error.py diff --git a/Assertion Error.py b/Assertion Error.py deleted file mode 100644 index 399606a..0000000 --- a/Assertion Error.py +++ /dev/null @@ -1,7 +0,0 @@ -def division(a,b): - assert b != 0 - return a/b - -print(division(10,2)) -print(division(10,0.5)) -print(division(10,0)) # AssertionError \ No newline at end of file From 12313a4aa76f4c60d80cc3e6c05851d19dcb72a0 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:42:59 +0530 Subject: [PATCH 060/132] Delete AttributeError.py --- AttributeError.py | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100644 AttributeError.py diff --git a/AttributeError.py b/AttributeError.py deleted file mode 100644 index 325623f..0000000 --- a/AttributeError.py +++ /dev/null @@ -1,12 +0,0 @@ -# s = "Hello to Errors" -# s.reverse() - -class Person: - def __init__(self, name, age): - self.name = name - self.age = age - def greet(self): - print(f'Hello, My name is {self.name})') - -p = Person('Ironman', 40) -p.city # AttributeError: 'Person' object has no attribute 'city' \ No newline at end of file From 19797cbe5233d1949e75b543c49348247433d0c4 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:43:09 +0530 Subject: [PATCH 061/132] Delete CSV_data_frame.py --- CSV_data_frame.py | 37 ------------------------------------- 1 file changed, 37 deletions(-) delete mode 100644 CSV_data_frame.py diff --git a/CSV_data_frame.py b/CSV_data_frame.py deleted file mode 100644 index 852cec4..0000000 --- a/CSV_data_frame.py +++ /dev/null @@ -1,37 +0,0 @@ -import pandas as pd - -sd = pd.read_csv('sales_demo.csv') -pr = pd.read_csv('products_demo.csv') - -print(type(sd), type(pr)) - -print(sd.shape) -print(pr.shape) - -print(sd.columns) - -print(pr['ProductID'].nunique()) -print(len(pr)) - -df = pd.merge(sd, pr, on = "ProductID", how = "inner") -print(df.shape) - -m_left = pd.merge(sd, pr, on = "ProductID", how = "left") -m_left1 = pd.merge(pr, sd, on = "ProductID", how = "left") - -print(m_left.shape, m_left1.shape) - -m_right = pd.merge(sd, pr, on = "ProductID", how = "right") -m_right1 = pd.merge(pr, sd, on = "ProductID", how = "right") - -print(m_right.shape, m_right1.shape) -m_outer = pd.merge(sd, pr, on = "ProductID", how = "outer") -m_outer1 = pd.merge(pr, sd, on = "ProductID", how = "outer") -print(m_outer.shape, m_outer1.shape) -print(m_outer, m_outer1) - -''' Inner join - common records from both data frames - Outer join - all reccords from both data frames - Left join - all records of left data frames - Right join - all records of right data frames''' - From 78425fdd41a1ea2e319390305894fc3a333945c2 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:43:47 +0530 Subject: [PATCH 062/132] Delete Creating a new worksheet.py --- Creating a new worksheet.py | 25 ------------------------- 1 file changed, 25 deletions(-) delete mode 100644 Creating a new worksheet.py diff --git a/Creating a new worksheet.py b/Creating a new worksheet.py deleted file mode 100644 index 54aa14a..0000000 --- a/Creating a new worksheet.py +++ /dev/null @@ -1,25 +0,0 @@ -import openpyxl as op - -wb = op.load_workbook('.\VideoSales.xlsx') -ws = wb.active -# ws = wb['SalesData'] -# wb.create_sheet('New Sheet') -# wb.save('VideoSales.xlsx') -# print(wb.sheetnames) - -# --------- Title of active sheet ------------- -print(ws.title) - -# --------- Rename a sheet ---------------- -# ws = wb['New Sheet1'] -# print(ws.title) -ws.title = 'A New Sheet' -# wb.save('VideoSales.xlsx') -# print(wb.sheetnames) -print(wb.sheetnames) - -# Duplicate a worksheet -new_ws = wb.copy_worksheet(wb['A New Sheet1']) -new_ws.title = 'A New Sheet' -wb.save('VideoSales.xlsx') -print(wb.sheetnames) \ No newline at end of file From 57b699ff31d0ba173312e4e37d0d8145a1542a29 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:43:56 +0530 Subject: [PATCH 063/132] Delete Exception Handling finally.py --- Exception Handling finally.py | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 Exception Handling finally.py diff --git a/Exception Handling finally.py b/Exception Handling finally.py deleted file mode 100644 index cfe014b..0000000 --- a/Exception Handling finally.py +++ /dev/null @@ -1,10 +0,0 @@ -n = int(input("Enter the numerator: ")) -try: - d = int(input("Enter the denominator: ")) - print(n/d) -except: - print("Error: Denominator cannot be a zero") -finally: - print("Division may have occurred") - ''' finally block is executed if the exception is identifed and handled - finally block is executed if the exception does not occur also''' \ No newline at end of file From 265149691d720906d51d59e503bc9dd513daa7ab Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:44:05 +0530 Subject: [PATCH 064/132] Delete Exception Handling.py --- Exception Handling.py | 28 ---------------------------- 1 file changed, 28 deletions(-) delete mode 100644 Exception Handling.py diff --git a/Exception Handling.py b/Exception Handling.py deleted file mode 100644 index e4d3069..0000000 --- a/Exception Handling.py +++ /dev/null @@ -1,28 +0,0 @@ -# Try and Except block - -n = int(input("Enter the numerator: ")) -try: - d = int(input("Enter the denominator: ")) - print(n/d) -except ZeroDivisionError as e: - print(f'ZeroDivisionError: {e}') - -n = int(input("Enter the numerator: ")) -d = int(input("Enter the denominator: ")) -print(n/d) - - -# Try except and else block - -try: - n = int(input("Enter a number: ")) - assert n%2 == 0 -except: - print("Not an even number") -else: - print(n/4) - - -''' Try - code where the error might occur - Except - what should be done if the error occurs - Else - what else should be done if the error does not occur''' \ No newline at end of file From 637ac2aaaf71768c88ec4c731f1ecc521d5758db Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:44:16 +0530 Subject: [PATCH 065/132] Delete File Exists Error.py --- File Exists Error.py | 5 ----- 1 file changed, 5 deletions(-) delete mode 100644 File Exists Error.py diff --git a/File Exists Error.py b/File Exists Error.py deleted file mode 100644 index fb0aee2..0000000 --- a/File Exists Error.py +++ /dev/null @@ -1,5 +0,0 @@ -def create_file(filepath): - open(filepath, 'x') # creates a file if it does not exists - print(f'{filepath} created successfully') - -create_file('new_file1.txt') # FileExistsError: [Errno 17] File exists: 'new_file1.txt' \ No newline at end of file From 5a108e83acd58b7c10b429652523204ef03f7826 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:44:25 +0530 Subject: [PATCH 066/132] Delete File NotFound Error.py --- File NotFound Error.py | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 File NotFound Error.py diff --git a/File NotFound Error.py b/File NotFound Error.py deleted file mode 100644 index 6cad074..0000000 --- a/File NotFound Error.py +++ /dev/null @@ -1,3 +0,0 @@ -f = open('new.txt', 'r') # r opens the file if it exists in read mode -print('File opened') -'''FileNotFoundError: [Errno 2] No such file or directory: 'new.txt' ''' \ No newline at end of file From d8b913db29fdeb0bc7dae4134266f267b54a4045 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:44:35 +0530 Subject: [PATCH 067/132] Delete File handling Assignment.py --- File handling Assignment.py | 36 ------------------------------------ 1 file changed, 36 deletions(-) delete mode 100644 File handling Assignment.py diff --git a/File handling Assignment.py b/File handling Assignment.py deleted file mode 100644 index 0fdbf78..0000000 --- a/File handling Assignment.py +++ /dev/null @@ -1,36 +0,0 @@ -# Assume that you have csv file of emp details that consist of name, empid, dept and sal. Read the file and compute the following values DA = 18% of sal, HRA = 2% of sal. -# Create an output file called as emp_sal.csv where empid, HRA, DA, Gross sal is written back. - -import csv - -# Input and output file names -input_file = "emp_details.csv" -output_file = "emp_sal.csv" - -with open(input_file, mode='r') as infile, open(output_file, mode='w', newline='') as outfile: - # Read CSV with semicolon delimiter - reader = csv.DictReader(infile, delimiter=';', skipinitialspace=True) - - # Output CSV header - fieldnames = ['Empid', 'HRA', 'DA', 'Gross'] - writer = csv.DictWriter(outfile, fieldnames=fieldnames) - writer.writeheader() - - for row in reader: - salary = float(row['Salary']) - - # Calculations - DA = 0.18 * salary - HRA = 0.02 * salary - Gross = salary + DA + HRA - - # Write to output CSV - writer.writerow({ - 'Empid': row['Empid'], - 'HRA': round(HRA, 2), - 'DA': round(DA, 2), - 'Gross': round(Gross, 2) - }) - -print("emp_sal.csv created successfully!") - From 7168722d2081f387bde31a8a08081ad2d32f30e4 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:44:45 +0530 Subject: [PATCH 068/132] Delete FileHandling(CSV).py --- FileHandling(CSV).py | 13 ------------- 1 file changed, 13 deletions(-) delete mode 100644 FileHandling(CSV).py diff --git a/FileHandling(CSV).py b/FileHandling(CSV).py deleted file mode 100644 index ee024a0..0000000 --- a/FileHandling(CSV).py +++ /dev/null @@ -1,13 +0,0 @@ -import csv - -# Read CSV files -with open('data.csv','r') as f: - read=csv.reader(f) - for r in read: - print(r) - - -with open('data1_8dec.csv','r') as f: - read=csv.reader(f, delimiter= ';', skipinitialspace= True) - for r in read: - print(r) \ No newline at end of file From 147337c0a6de28c20b672a95558889133e2b25c9 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:44:54 +0530 Subject: [PATCH 069/132] Delete IO Error.py --- IO Error.py | 5 ----- 1 file changed, 5 deletions(-) delete mode 100644 IO Error.py diff --git a/IO Error.py b/IO Error.py deleted file mode 100644 index bf25091..0000000 --- a/IO Error.py +++ /dev/null @@ -1,5 +0,0 @@ -try: - f = open('new.txt', 'r') - print('File Opened') -except IOError as e: - print(f'IOError: {e}') \ No newline at end of file From 422bf277c369c3bafd80332c0592692a7782b96c Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:45:04 +0530 Subject: [PATCH 070/132] Delete Json file handling.py --- Json file handling.py | 47 ------------------------------------------- 1 file changed, 47 deletions(-) delete mode 100644 Json file handling.py diff --git a/Json file handling.py b/Json file handling.py deleted file mode 100644 index 73187b4..0000000 --- a/Json file handling.py +++ /dev/null @@ -1,47 +0,0 @@ -import json as j - -p = '{"name":"Alpha","age":30}' -p_dict = j.loads(p) -print(type(p), type(p_dict)) - -# with open('Json file1.json','r') as f: -# p_json = j.load(f) -# print(type(p_json)) -# print(p_json) - -# with open('Json file2.json','r') as f: -# p2_json = j.load(f) -# print(type(p2_json)) -# print(p2_json) - -# print(p2_json[0]["name"]) -# for r in p2_json: - # print(r['name']) - -print("Json file3") -with open('Json file3.json','r') as f: - p3_json = j.load(f) - print(type(p3_json)) - print(p3_json) - print(p3_json['alpha']['city']) - for r in p3_json: - print(f'Name : {r}') - print(f"Age: {p3_json[r]['age']}") - print(f"City: {p3_json[r]['city']}") - -# ----------- Writing the JSON objects------------ - -n_dict = {'name':'Delta','age':25} -n_json = j.dumps(n_dict) -print(type(n_dict),type(n_json)) -print(n_dict) -print(n_json) - -with open('Json file4.json','w') as f: - j.dump(n_dict, f) - -with open('Json file4.json','a') as f: - j.dump(n_dict,f) - -with open('Json file4.txt','w') as f: - j.dump(n_dict, f) \ No newline at end of file From 06e56d77ae6a896a6f374312837b28d690bbc60a Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:45:16 +0530 Subject: [PATCH 071/132] Delete KeyboardInterrupt Error.py --- KeyboardInterrupt Error.py | 1 - 1 file changed, 1 deletion(-) delete mode 100644 KeyboardInterrupt Error.py diff --git a/KeyboardInterrupt Error.py b/KeyboardInterrupt Error.py deleted file mode 100644 index 80d788c..0000000 --- a/KeyboardInterrupt Error.py +++ /dev/null @@ -1 +0,0 @@ -name = input("Enter the value") \ No newline at end of file From ba503f0b60d2eb21f1337d4051048627fd7ee02b Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:45:25 +0530 Subject: [PATCH 072/132] Delete file excel handling.py --- file excel handling.py | 100 ----------------------------------------- 1 file changed, 100 deletions(-) delete mode 100644 file excel handling.py diff --git a/file excel handling.py b/file excel handling.py deleted file mode 100644 index eda118a..0000000 --- a/file excel handling.py +++ /dev/null @@ -1,100 +0,0 @@ -import openpyxl as op -# load the workbook -wb = op.load_workbook('.\VideoSales.xlsx') -# print(type(wb)) # - -# print(wb) # - -# Call the active worksheet -ws = wb.active -# print(type(ws)) - -# Call the sheet by it's name -ws = wb['SalesData'] -# print(ws) # - -# Count the number of rows and columns that are filled in the worksheet -# print(f'Total number of rows is {ws.max_row} and total number of columns is {ws.max_column}') - -# Read the data from a cell -# print(f"The value stored in cell D5 is: {ws['D5'].value}") - -# Read data from multiple cells -values = [ - ws.cell(row = 1, column = i).value - for i in range(1, ws.max_column + 1) -] -# print(values) - -data = [ - ws.cell(row = 1, column = i).value - for i in range(1, ws.max_column + 1) -] -# print(values) - -# Reading data from a range of cells -list1 = list() -for value in ws.iter_rows(min_row = 1, max_row = 5, min_col = 1, max_col = 4, values_only = True): - list1.append(value) -# print(list1) - -# Display the values in a tabular method -for e1,e2,e3,e4 in list1: - '''unpacking of a tuple''' - # (print("{:<10}{:<35}{:<10}{:<5}".format(e1,e2,e3,e4))) - '''width of 1st column is 10, 2nd column is 35, 3rd column is 10, 4th column is 5''' - -# Write to a cell -ws['K1'] = 'Total Sales' - -# Add a new row -# new_row = ( -# 31, 'Cricket Premier League', 'PC', 2025, 'Sports', -# 'GameStudio', 2.60, 1.40, 3.80, 2.20, 10.0 -# ) -# ws.append(new_row) -# wb.save('VideoSales.xlsx') -# print(ws.max_row) - -# Delete a row -# ws.delete_rows(ws.max_row, 1) -# '''First parameter - row number from where the deletion starts. -# Second parameter - How many rows are to be deleted''' -# print(ws.max_row) -# wb.save('VideoSales.xlsx') -# print(ws.max_row) - -# ------------ Excel Formulas ---------------- - -# Average -ws['M1'] = 'Average Sales' -ws['M2'] = 'AVERAGE(K2:K31)' -wb.save('VideoSales.xlsx') - -# CountA -'''It counts the number of cells that are populated in a given range''' -# new_row = ( -# 29, 'Cricket Premier League', 'PC', ' ', 'Sports', -# 'GameStudio', 2.60, 1.40, 3.80, 2.20, 10.0 -# ) -# ws.append(new_row) -# wb.save('VideoSales.xlsx') -# print(ws.max_row) - -# ws['N1'] = 'Number of rows that have the value' -# ws['N2'] = '=COUNTA(D1:D32)' -# wb.save('VideoSales.xlsx') - -# Countif -'''This counts the number of cells that meet a criteria''' -# ws['01'] = 'Number of rows with Sports Genre' -# ws['02'] = 'COUNTIF(E2:E32, "Sports")' -# wb.save('VideoSales.xlsx') - -# Sumif -ws['M5'] = 'Total Sports Sales' -ws['M6'] = '=SUMIF(E2:E32, "Sports", K2:K32)' -'''First parameter - where should the criteria be checked - Second parameter - what is the criteria - Third parameter - what should be summed''' -wb.save('VideoSales.xlsx') From f725a5fdcfb396f6e12682a203d33cb72d49744e Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:45:35 +0530 Subject: [PATCH 073/132] Delete file handling dictreader.py --- file handling dictreader.py | 21 --------------------- 1 file changed, 21 deletions(-) delete mode 100644 file handling dictreader.py diff --git a/file handling dictreader.py b/file handling dictreader.py deleted file mode 100644 index b91c052..0000000 --- a/file handling dictreader.py +++ /dev/null @@ -1,21 +0,0 @@ -import csv - -with open('data1_8dec.csv','r') as f: - read_dict = csv.DictReader(f) - for r in read_dict: - print(r) -# print(type(r)) - -# with open('data2_8dec.csv','r') as f: -# read_dict = csv.DictReader(f, delimiter=';', skipinitialspace=True) -# for r in read_dict: -# print(r) - -with open('data2_8dec.csv','r') as f: - fnames = ['Name', 'Age', 'Profession'] - read_dict = csv.DictReader(f, fieldnames= fnames, delimiter=';', skipinitialspace=True) - for r in read_dict: - print(r) - -print(type(read_dict)) -print(type(r)) \ No newline at end of file From fe0b3fe3e13e9256f3bc0934e007d646bf28f5c2 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:45:44 +0530 Subject: [PATCH 074/132] Delete import this.py --- import this.py | 23 ----------------------- 1 file changed, 23 deletions(-) delete mode 100644 import this.py diff --git a/import this.py b/import this.py deleted file mode 100644 index 9c3b721..0000000 --- a/import this.py +++ /dev/null @@ -1,23 +0,0 @@ -import this - -'''The Zen of Python, by Tim Peters - -Beautiful is better than ugly. -Explicit is better than implicit. -Simple is better than complex. -Complex is better than complicated. -Flat is better than nested. -Sparse is better than dense. -Readability counts. -Special cases aren't special enough to break the rules. -Although practicality beats purity. -Errors should never pass silently. -Unless explicitly silenced. -In the face of ambiguity, refuse the temptation to guess. -There should be one-- and preferably only one --obvious way to do it. -Although that way may not be obvious at first unless you're Dutch. -Now is better than never. -Although never is often better than *right* now. -If the implementation is hard to explain, it's a bad idea. -If the implementation is easy to explain, it may be a good idea. -Namespaces are one honking great idea -- let's do more of those!''' \ No newline at end of file From 348efee667a32ac799d6896bd1d81e2b882f4afb Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:46:01 +0530 Subject: [PATCH 075/132] Delete Multiple Exception Handling.py --- Multiple Exception Handling.py | 9 --------- 1 file changed, 9 deletions(-) delete mode 100644 Multiple Exception Handling.py diff --git a/Multiple Exception Handling.py b/Multiple Exception Handling.py deleted file mode 100644 index 3cec7e3..0000000 --- a/Multiple Exception Handling.py +++ /dev/null @@ -1,9 +0,0 @@ -try: - l = [0, 2, 4, 6, 8, 10] - i1 = int(input("Enter the first index")) - i2 = int(input("Enter the second index")) - print(l[i1]/l[i2]) -except IndexError as e: - print(f'IndexError: {e}. Check the index number') -except ZeroDivisionError as e: - print(f'ZeroDivisionError: {e}. The index is pointing to a 0 value') From f69addbb6b766d8b13b6c4f3b85d620cc146ae20 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:46:10 +0530 Subject: [PATCH 076/132] Delete Name Error.py --- Name Error.py | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 Name Error.py diff --git a/Name Error.py b/Name Error.py deleted file mode 100644 index 7d7a5b6..0000000 --- a/Name Error.py +++ /dev/null @@ -1,8 +0,0 @@ -# x = 10 -# z = x + y # NameError: name 'y' is not defined -# print(z) - -x = '10' -y = 10 -z = x+y # TypeError: can only concatenate str (not "int") to str -print(z) \ No newline at end of file From b3e4fbb54450faea06cf4b54d71743e2d9bb31e7 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 11:46:19 +0530 Subject: [PATCH 077/132] Delete KeyError.py --- KeyError.py | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 KeyError.py diff --git a/KeyError.py b/KeyError.py deleted file mode 100644 index 7726824..0000000 --- a/KeyError.py +++ /dev/null @@ -1,10 +0,0 @@ -# d = {'name' : 'Alpha', 'age':20, 'city':'Bengaluru'} -# print(d['address']) # KeyError: 'address' - - -# LookupError -try: - d = {'name' : 'Alpha', 'age':20, 'city':'Bengaluru'} - d['address'] -except LookupError as e: - print(f'LookupError: {e}') From ab30760889c58530a745df0de6cc4f8544d8b9ec Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 8 Mar 2026 17:21:38 +0530 Subject: [PATCH 078/132] Update README.md --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index bc8d9a9..e5b2b04 100644 --- a/README.md +++ b/README.md @@ -15,13 +15,13 @@ A professional, structured collection of Python scripts and logic implementation ## 📂 Project Structure -```plaintext +``` pythonnew/ -├── scripts/ # Individual utility and automation scripts -├── modules/ # Reusable logic components and classes -├── tests/ # Unit tests for script verification -├── docs/ # Technical documentation -└── requirements.txt # List of project dependencies +├── IOT/ # Programs related to IoT and data visualization +├── unit_1/ # Python programs from Unit 1 +├── unit_2/ # Python programs from Unit 2 +├── unit_3/ # Python programs from Unit 3 +└── README.md # Project documentation ``` --- From 55f8d836b0d229e536eceae72e38df33947f504a Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Mon, 9 Mar 2026 22:20:20 +0530 Subject: [PATCH 079/132] Create Overflow Error.py --- unit_3/Overflow Error.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 unit_3/Overflow Error.py diff --git a/unit_3/Overflow Error.py b/unit_3/Overflow Error.py new file mode 100644 index 0000000..1dfe1f2 --- /dev/null +++ b/unit_3/Overflow Error.py @@ -0,0 +1,16 @@ +import math +# math.exp(1000) # OverflowError: math range error +# pow(3.14,1000) # OverflowError: (34, 'Result too large') + +def fact_cal(n): + r = 1 + for i in range(1, n+1): + r*=i + return r +# print(fact_cal(1000)) + +# print(fact_cal(40000)) + +# ZeroDivisionError +print(10.0/0) +print(10/0) From 230bba8869f9287db07148db80f8e625bf7573ca Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Mon, 9 Mar 2026 22:21:04 +0530 Subject: [PATCH 080/132] Create pandas_csv.py --- unit_3/pandas_csv.py | 225 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 225 insertions(+) create mode 100644 unit_3/pandas_csv.py diff --git a/unit_3/pandas_csv.py b/unit_3/pandas_csv.py new file mode 100644 index 0000000..d31a776 --- /dev/null +++ b/unit_3/pandas_csv.py @@ -0,0 +1,225 @@ +import pandas as pd + +df = pd.read_csv('sales_r.csv') + +print(df.shape) # Inspection +print(df.columns) +print(df.index) # Shows the numbering of rows +print(df.dtypes) # Shows the data types of individual columns +print(df.head(3)) # To display n number of records +print(df.tail(3)) # To display n number of records from last + +# ------- Preprocessing of data --------------- +# Check for NaN Values in columns +print(df.isna()) +print(df.isna().sum()) + +# Check for NaN Values in rows +print(df.isna().any(axis = 1)) + +print(df.isna().any(axis = 1).sum()) # 8 + +# Check for not NaN Values in columns +print(df.notna()) +print(df.notna().sum()) + +# Check for not NaN Values in rows +print(df.notna().any(axis = 1)) +print(df.notna().any(axis = 1).sum()) # 10 + +# Clean the column names +df.columns = df.columns.str.strip() +print(df.columns) + +print(df.head) +# Remove quotes, commas from a particular column +# Step 1: Convert column amount to str +# Step 2: Replace quotes +# Step 3: Replace comma +# Step 4: Extract the numeric digits + +df['Amount'] = ( + df['Amount'].astype(str) + .str.replace('"','',regex = False) + .str.replace(',','',regex = False) + .str.extract(r'(\d+)',expand = False) +) +print(df.dtypes) + +print(df['Amount']) + +# Nan values can be replaced with +# 1. median - mid value +# 2. mean - average value +# 3. mode - value that has highest frequency +# Only if the column is numeric + +# Convert column to numeric +df['Amount'] = pd.to_numeric(df['Amount'], errors= 'coerce') +'''First parameter - column that has to be converted + errors = coerce (all non-numeric characters will be converted as NaN)''' +print(df.dtypes) + +# Fill NaN values with median +df['Amount'] = df['Amount'].fillna(df['Amount'].median()) +print(df['Amount']) +print(df['Qty']) + +# Replace space in Qty with mean +df['Qty'] = pd.to_numeric(df['Qty'], errors='coerce') +print(df.dtypes) +print(df['Qty']) + +# Fill Qty's NaN values with mean +df['Qty'] = df['Qty'].fillna(df['Qty'].mean()) +print(df['Qty']) +print(df.head) + +# Drop Columns +# 1. If the column contains too many NaN +# 2. If it is an unwanted column + +df = df.dropna(axis=1, how = 'all') +print(df.columns) # Still there are 6 unnamed + +df = df.dropna(axis=1, how = 'any') +print(df.columns) + +# Equivalent commands +# df = df.drop(columns=['Unnamed: 6']) + +# Drop columns given the exact name of the column +# df = df.iloc[:,:-1] +# df = df.loc[:,~df.columns.str.contains('^Unnamed')] + +# print(df['Region']) + +# Standardize Text Columns +df['Region'] = df['Region'].str.strip().str.lower() + +print(df['Region']) + +# Remove quotes in all columns +df = df.apply(lambda c : c.astype(str).str.replace('"','',regex = False)) +print(df) + +# 1. Convert the Region to numeric. All non-numeric values become NaN +# 2. Create a boolean mask. It is True when Region is 500 or 800 +# 3. Replace all such rows with Region as North + +df.loc[pd.to_numeric(df['Region'],errors='coerce') + .isin([500,800]), 'Region']= 'north' +print(df) + +# Filter data based on conditions +df['Amount'] = pd.to_numeric(df['Amount'], errors='coerce') +hsales = df['Amount'] > 2000 + +print(type(hsales)) +print(hsales) + +# Create a data frame based on the filter +df_high = df[hsales] +print(type(df_high)) +print(df_high) + +# To count the number of records or rows in a Dataframe +# print(len(df)) # 10 +# print(len(df_high)) # 4 + +# Filtering based on multiple conditions +c_amt = df['Amount']>2000 +c_reg = df['Region'] == 'south' +print(type(c_amt), type(c_reg)) + +# Conditions can be & or | +df_t1 = df[c_amt & c_reg] +df_t2 = df[c_amt | c_reg] +df_t3 = df[c_reg | c_amt] +df_t4 = df[c_reg & c_amt] +print(len(df_t1), len(df_t2)) +print(len(df_t3), len(df_t4)) + +print(df_t1) + +# Sort the values in column +df_sort = df.sort_values('Amount') +print('\n',df_sort) +df_desc = df.sort_values('Amount', ascending = False) +print('\n',df_desc) + +df_s1 = df.sort_values(['Region', 'Amount']) +print('\n',df_s1) + +df_s2 = df.sort_values(['Region', 'Amount'], ascending = [True, False]) # Region - Ascending, Amount - Descending +print('\n',df_s2) + +# Create new columns based on existing columns + +df['Tax'] = df['Amount']*0.18 +print(df.columns) +print(df.dtypes) +print(df) + +df['Total_Tax'] = df['Amount'] + df['Tax'] +print('\n',df['Total_Tax']) + +# ------- Profiling the columns ---------- +# 1. Count the values +print(df['Region'].value_counts()) +print() +print(df['Amount'].value_counts()) + +# 2. Summarize the data frame +print(df['Amount'].describe()) +print() +print(df['Region'].describe()) +print() +print(df['City'].describe()) +print() + +# 3. Grouping the data +grp_reg = df.groupby('Region') +print(type(grp_reg), len(grp_reg), grp_reg) + +# ------ View the grouped data ------ +# 1. View thw group names +print(grp_reg.groups.keys()) + +# 2. View the row index that belongs to each group +print(grp_reg.groups) + +# 3. View specific group +print() +print(grp_reg.get_group('north')) + +# 4. Loop through all the groups +for n, g in grp_reg: + print(f'Group: {n}') + print(g) + +# Grouping based on multiple columns +grp_mul = df.groupby(['Region', 'City']) +print() +print(grp_mul.groups) +print() + +# Sum of the amount af each region +sales_reg = grp_reg['Amount'].sum() +print(sales_reg) +print() + +# Multiple Aggression +region_summary = grp_reg['Amount'].agg(['sum', 'mean', 'count']) +print(region_summary) + +# Custom Aggression +summary = df.groupby('Region').agg( + Total_Amt = ('Amount', 'sum'), + Avg_Amt = ('Amount', 'mean'), + Avg_Tax = ('Tax', 'mean'), + Unique_City = ('City', 'nunique') +) +print(type(summary)) # +print() +print(summary) From e65ac07fc8709a47ed73dd05cc5fc2c8d7957ba6 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Mon, 9 Mar 2026 22:21:35 +0530 Subject: [PATCH 081/132] Create pandas_new.py --- unit_3/pandas_new.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 unit_3/pandas_new.py diff --git a/unit_3/pandas_new.py b/unit_3/pandas_new.py new file mode 100644 index 0000000..73adf41 --- /dev/null +++ b/unit_3/pandas_new.py @@ -0,0 +1,44 @@ +import pandas as pd + +# Create a dataframe from a dictionary +data = {'Name' : ['Amora', 'Beast', 'Captain America'], + 'Age': [25, 30, 25], + 'City': ['New York', 'London', 'Paris']} + +df = pd.DataFrame(data) +# print(type()) +print(df) + +# Create a dataframe from a list +data = [['Deadpool',25,'New York'], + ['Elektra',24,'Paris'], + ['Falcon',30,'London']] +df1 = pd.DataFrame(data) +print('\n', df1,'\n') +df2 = pd.DataFrame(data, columns=['Name','Age','City']) +print(df2) + +# Create a dataframe from a file +# df5 = pd.read_csv('datapandas.csv') +# print('CSV \n',df5) + +# df6 = pd.read_json('datapandas.json') +# print('Json\n',df6) + +df7 = pd.read_excel("VideoSales.xlsx") +print(df7) + +# ------------------------------- +# Inspection Mothods +# ------------------------------- + +print(df7.head()) +print(df7.tail()) +print(df7.loc[0:3]) +print(df7.loc[5:9,['Name','Genre']]) + +print(df7.isna().any(axis=1).sum()) # Check for missing values +print(df7.info()) # Summary of the dataframe +print(df7.describe()) # Statistical summary of numerical columns + +print(df7.notna()) From 1f5029b0b09c1172b4a76fe2f3631ca14fe24cfc Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Mon, 9 Mar 2026 22:22:05 +0530 Subject: [PATCH 082/132] Create partices.py --- unit_3/partices.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 unit_3/partices.py diff --git a/unit_3/partices.py b/unit_3/partices.py new file mode 100644 index 0000000..9c4a7d8 --- /dev/null +++ b/unit_3/partices.py @@ -0,0 +1,29 @@ +# Logical errors + +# def fact_cal(n): +# r = 1 +# for i in range(n): +# r = r*i +# print(r) + +# fact_cal(3) + +# Corrected code +def fact_cal(n): + r = 1 + for i in range(1, n+1): + r = r*i + print(r) +fact_cal(3) + +# Runtime Errors or Exceptions +'''List of exceptions handled in Python''' + +import builtins +l = [name for name in dir(builtins) + if isinstance(getattr(builtins, name), type) + and + issubclass(getattr(builtins, name), BaseException)] +print('List of exceptions in Python\n') +for i in l: + print(i, end = " ") From 359b2da719fa3d9d6ab717b1b19b5cf43840428a Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Mon, 9 Mar 2026 22:22:36 +0530 Subject: [PATCH 083/132] Create Sales_SalesQ2.py --- unit_3/Sales_SalesQ2.py | 66 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 unit_3/Sales_SalesQ2.py diff --git a/unit_3/Sales_SalesQ2.py b/unit_3/Sales_SalesQ2.py new file mode 100644 index 0000000..1ae711f --- /dev/null +++ b/unit_3/Sales_SalesQ2.py @@ -0,0 +1,66 @@ +import pandas as pd + +# -------------------------------------------------- +# Read CSV files +# -------------------------------------------------- +s1 = pd.read_csv('sales.csv') +s2 = pd.read_csv('sales_q2.csv') + +# -------------------------------------------------- +# Check whether the two DataFrames have the same structure +# -------------------------------------------------- +print("Shapes:") +print(s1.shape, s2.shape) + +print("\nColumns in s1:") +print(s1.columns) + +print("\nColumns in s2:") +print(s2.columns) + +# -------------------------------------------------- +# Combine two DataFrames vertically +# -------------------------------------------------- + +# ignore_index=True -> resets index from 0 continuously +s_all = pd.concat([s1, s2], ignore_index=True) + +# ignore_index=False (default) -> keeps original indices +s_all1 = pd.concat([s1, s2]) + +print("\nShapes after concatenation:") +print(s_all.shape, s_all1.shape) + +# -------------------------------------------------- +# Preview data +# -------------------------------------------------- +print("\nHead of s_all (ignore_index=True):") +print(s_all.head()) + +print("\nHead of s_all1 (original indices kept):") +print(s_all1.head()) + +# -------------------------------------------------- +# Export DataFrames +# -------------------------------------------------- + +# CSV export +s_all.to_csv('sales_all.csv', index=False) # without index +s_all.to_csv('sales_all_1.csv') # with index + +# Excel export +s_all1.to_excel('sales_all.xlsx', index=False) + +# JSON export +s_all.to_json('sales_all.json', index=False) +s_all.to_json('sales_all_1.json') + +# XML export +s_all.to_xml('sales_all.xml', index=False, parser='etree') +s_all.to_xml('sales_all_1.xml', parser='etree') + +# -------------------------------------------------- +# Notes: +# index=False -> index is not written to file +# index=True -> index is written as an extra column (default) +# -------------------------------------------------- From 3d91f8dfbe6df5fca27c69cb5fd0727585ba5baf Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Mon, 9 Mar 2026 22:23:02 +0530 Subject: [PATCH 084/132] Create tempCodeRunnerFile.py --- unit_3/tempCodeRunnerFile.py | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 unit_3/tempCodeRunnerFile.py diff --git a/unit_3/tempCodeRunnerFile.py b/unit_3/tempCodeRunnerFile.py new file mode 100644 index 0000000..82903f0 --- /dev/null +++ b/unit_3/tempCodeRunnerFile.py @@ -0,0 +1,2 @@ +', index = False) +# s_all.to_xml('sales_all_1.xml') From df8f6208825fc9c412b62e8ae72e96eca5f24057 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Mon, 9 Mar 2026 22:23:36 +0530 Subject: [PATCH 085/132] Create Unbounded Local Error.py --- unit_3/Unbounded Local Error.py | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 unit_3/Unbounded Local Error.py diff --git a/unit_3/Unbounded Local Error.py b/unit_3/Unbounded Local Error.py new file mode 100644 index 0000000..7c81ad9 --- /dev/null +++ b/unit_3/Unbounded Local Error.py @@ -0,0 +1,6 @@ +def fact_cal(n): + for i in range(1, n+1): + r = r*i # UnboundLocalError: local variable 'r' referenced before assignment + return r + +print(fact_cal(5)) From 9fefe9292645e7a0f33a54c3d639653aa6bb08b9 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Mon, 9 Mar 2026 22:24:00 +0530 Subject: [PATCH 086/132] Create value Error.py --- unit_3/value Error.py | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 unit_3/value Error.py diff --git a/unit_3/value Error.py b/unit_3/value Error.py new file mode 100644 index 0000000..219cc1b --- /dev/null +++ b/unit_3/value Error.py @@ -0,0 +1,2 @@ +v = int("Hello") +print(v) # ValueError: invalid literal for int() with base 10: 'Hello' From b094f6bee75efd05c32f9328e9c994f19cd15a2e Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Mon, 9 Mar 2026 22:24:27 +0530 Subject: [PATCH 087/132] Create XML employee.py --- unit_3/XML employee.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 unit_3/XML employee.py diff --git a/unit_3/XML employee.py b/unit_3/XML employee.py new file mode 100644 index 0000000..9649817 --- /dev/null +++ b/unit_3/XML employee.py @@ -0,0 +1,30 @@ +0import xml.etree.ElementTree as xml +employees=[ + {'Name':"Shannu", + "Age": 23, + 'Salary':240000}, + {'Name':"Keerthi", + "Age": 23, + 'Salary':24000}, + {'Name':"Mindri", + "Age": 2, + 'Salary':0} + ] + +root=xml.Element("employees") +# print(employees) + +for emp in employees: + b_element=xml.Element('Employees') + root.append(b_element) + b_element.set('Employees',employees['Employee']) + name = xml.SubElement(b_element, 'Name') + name.text = employees['Name'] + age = xml.SubElement(b_element, 'Age') + age.text = employees['Age'] + sal = xml.SubElement(b_element, 'Salary') + sal.text = float(employees['Salary']) +tree = xml.ElementTree(root) + +with open('Employees.xml', 'wb') as fh: + tree.write(fh) From aa0a158cf3ee0b57780ca027fbcfb5f2cd4632bf Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Mon, 9 Mar 2026 22:25:29 +0530 Subject: [PATCH 088/132] Create xml_file.py --- unit_3/xml_file.py | 80 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 unit_3/xml_file.py diff --git a/unit_3/xml_file.py b/unit_3/xml_file.py new file mode 100644 index 0000000..65727c5 --- /dev/null +++ b/unit_3/xml_file.py @@ -0,0 +1,80 @@ +import xml.etree.ElementTree as xml +books=[ + {'Title':"Pride and Prejustice", + "Author":'Jane Austen', + 'Price':240, + 'Category':'Fiction'}, + {'Title':"The Diary of young girl", + "Author":'Anne Frank', + 'Price':500, + 'Category':'Non-Fiction'}, + {'Title':"Five on a Treasure Island", + "Author":'Enid Blyton0', + 'Price':250, + 'Category':'Fiction'}] + +root=xml.Element("Books") +# print(type(root)) +for book in books: + b_element=xml.Element('Book') + root.append(b_element) + b_element.set('Category',book['Category']) + '''First parameter - attribute name''' + '''Second parameter - attribute value''' + title = xml.SubElement(b_element, 'Title') + '''First parameter - parent node''' + '''Second parameter - name of the child node''' + title.text = book['Title'] + author = xml.SubElement(b_element, 'Author') + author.text = book['Author'] + price = xml.SubElement(b_element, 'Price') + price.text = str(book['Price']) +tree = xml.ElementTree(root) + +with open('Book.xml', 'wb') as fh: + tree.write(fh) + +# print('Books.xml file has been created') + +# print(type(b_element),'\n',type(title),'\n',type(author), '\n',type(price)) + +# print(title) +# print(title.text) + +tree = xml.ElementTree(file = 'Book.xml') +root = tree.getroot() +books = [] +# print(type(tree), type(root), type(books)) + +for book in root.findall('Book'): + b_data = {} + b_data['Category'] = book.get('Category') + '''Get the attribute and its value''' + for d in book: + '''Get each child element for every parent''' + b_data[d.tag] = d.text + books.append(b_data) +# print(type(b_data),'\n',type(d),'\n',type(book)) +print(books) + +# ------------------------------------------- +# Modification of a XML file +# ------------------------------------------- + +tree = xml.ElementTree(file='Book.xml') +root=tree.getroot() + +# Iterate over prce +for p_ele in root.iter('Price'): + p = int(p_ele.text) + '''Convert the string value into an integer''' + p+=20 + p_ele.text = str(p) + '''Convert the element's value to a string''' + '''Since all values are stored as strings in XML''' + +# Write the new data back into an XML file +with open('Book.xml','wb') as f: + tree.write(f) + +print('Prices Updated') From 215974ee2255bfc46c93eb2ef31b5b0ef9284729 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 10 Mar 2026 21:43:50 +0530 Subject: [PATCH 089/132] Create Exception Handling during API calls.py --- .../Exception Handling during API calls.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Unit_4/APL Integration/Exception Handling during API calls.py diff --git a/Unit_4/APL Integration/Exception Handling during API calls.py b/Unit_4/APL Integration/Exception Handling during API calls.py new file mode 100644 index 0000000..42e7297 --- /dev/null +++ b/Unit_4/APL Integration/Exception Handling during API calls.py @@ -0,0 +1,18 @@ +import requests as req + +try: + response = req.get('https://dummyjson.com/posts/2400') + response.raise_for_status() + # Raise an exception for 4**, 5** errors + data = response.json() + print(f'Retrived {len(data)} records') +except req.exceptions.HTTPError as e: + print(f'HTTP Error: {e}') +except req.exceptions.ConnectionError as e: + print(f'Connection Error: Check internet connection {e}') +except req.exceptions.Timeout as e: + print(f'Timeout Error: Took too long to respond {e}') +except req.exceptions.RequestException as e: + print(f'Error in making request {e}') +except ValueError: + print('Error in passing the JSN response') From d139e6302303030ad31ce7db1ffb03c2bb647823 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 10 Mar 2026 21:44:18 +0530 Subject: [PATCH 090/132] Create fetch API --- Unit_4/APL Integration/fetch API | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Unit_4/APL Integration/fetch API diff --git a/Unit_4/APL Integration/fetch API b/Unit_4/APL Integration/fetch API new file mode 100644 index 0000000..155d634 --- /dev/null +++ b/Unit_4/APL Integration/fetch API @@ -0,0 +1,30 @@ +import requests as req +import xml.etree.cElementTree as et + +response = req.get('https://dummyjson.com/posts/120') + +if response.status_code == 200: + print('Request Successful') +else: + print(f'Request failed: {response.status_code}') + +print(type(response.text), response.text) + +data = response.json() +print(data) + +root = et.Element("post") + +id_el = et.SubElement(root, "id") +id_el.text = str(data["id"]) + +title_el = et.SubElement(root, "title") +title_el.text = str(data["title"]) + +user_el = et.SubElement(root, "userId") +user_el.text = str(data["userId"]) + +tree = et.ElementTree(root) +tree.write("api_data.xml", encoding="utf-8", xml_declaration=True) + +print("Data stored successfully.") From 4e3ecec09c209600ece7632e1836a2b4b72e88ef Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 10 Mar 2026 21:44:53 +0530 Subject: [PATCH 091/132] Create Multiple API data int a JSON file.py --- .../Multiple API data int a JSON file.py | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Unit_4/APL Integration/Multiple API data int a JSON file.py diff --git a/Unit_4/APL Integration/Multiple API data int a JSON file.py b/Unit_4/APL Integration/Multiple API data int a JSON file.py new file mode 100644 index 0000000..692be0e --- /dev/null +++ b/Unit_4/APL Integration/Multiple API data int a JSON file.py @@ -0,0 +1,29 @@ +import requests as r +import json + +response = r.get("https://dummyjson.com/posts") + +# Convert the data into JSON object +data = response.json() +print(data) + +# ---------------------------- +# Save the data into JSON file +# ---------------------------- + +# Process data into individual records +posts_list = [] +for post in data['posts']: + posts_list.append({'id': post['id'], + 'title': post['title'], + 'body': post['body'], + 'userId': post['userId'], + 'reactions': post['reactions']} + ) +print() +print(posts_list) + +# Store the data into a JSON file +with open('api_data_1.json', 'w') as f: + json.dump(posts_list, f, indent = 4) +print('Data stored successfully!') From a5a6f0ac43958db7ea1e93a181e5e7980f6359d5 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 10 Mar 2026 21:45:59 +0530 Subject: [PATCH 092/132] Create Request CSV.py --- Unit_4/APL Integration/Request CSV.py | 29 +++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Unit_4/APL Integration/Request CSV.py diff --git a/Unit_4/APL Integration/Request CSV.py b/Unit_4/APL Integration/Request CSV.py new file mode 100644 index 0000000..692be0e --- /dev/null +++ b/Unit_4/APL Integration/Request CSV.py @@ -0,0 +1,29 @@ +import requests as r +import json + +response = r.get("https://dummyjson.com/posts") + +# Convert the data into JSON object +data = response.json() +print(data) + +# ---------------------------- +# Save the data into JSON file +# ---------------------------- + +# Process data into individual records +posts_list = [] +for post in data['posts']: + posts_list.append({'id': post['id'], + 'title': post['title'], + 'body': post['body'], + 'userId': post['userId'], + 'reactions': post['reactions']} + ) +print() +print(posts_list) + +# Store the data into a JSON file +with open('api_data_1.json', 'w') as f: + json.dump(posts_list, f, indent = 4) +print('Data stored successfully!') From 80ae05c2fbf222ceaea9e9eb3cf2dd386c200056 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 10 Mar 2026 21:46:35 +0530 Subject: [PATCH 093/132] Create Request XML.py --- Unit_4/APL Integration/Request XML.py | 33 +++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Unit_4/APL Integration/Request XML.py diff --git a/Unit_4/APL Integration/Request XML.py b/Unit_4/APL Integration/Request XML.py new file mode 100644 index 0000000..3affcaa --- /dev/null +++ b/Unit_4/APL Integration/Request XML.py @@ -0,0 +1,33 @@ +import requests as req +import xml.etree.ElementTree as ET + +response = req.get('https://dummyjson.com/posts') +data = response.json() + +root = ET.Element('posts') + +for item in data['posts']: + p_el = ET.SubElement(root, "post") + + id_el = ET.SubElement(p_el, "Id") + id_el.text = str(item["id"]) + + t_el = ET.SubElement(p_el, "Title") + t_el.text = str(item["title"]) + + u_el = ET.SubElement(p_el, "UserId") + u_el.text = str(item["userId"]) + + v_el = ET.SubElement(p_el, "Views") + v_el.text = str(item["views"]) + +# Create ElementTree AFTER the loop +tree = ET.ElementTree(root) + +tree.write( + 'api_data_1.xml', + encoding='utf-8', + xml_declaration=True +) + +print('Data stored successfully') From eda827ba97343bfb593cca56bc8eafc428bf841f Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 10 Mar 2026 21:47:57 +0530 Subject: [PATCH 094/132] Create SAve single API data into CSV file.py --- .../SAve single API data into CSV file.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Unit_4/APL Integration/SAve single API data into CSV file.py diff --git a/Unit_4/APL Integration/SAve single API data into CSV file.py b/Unit_4/APL Integration/SAve single API data into CSV file.py new file mode 100644 index 0000000..5f58546 --- /dev/null +++ b/Unit_4/APL Integration/SAve single API data into CSV file.py @@ -0,0 +1,15 @@ +import requests as r +import json +import csv + +response = r.get("https://dummyjson.com/posts/149") + +# Convert the data into JSON object +data = response.json() + +#save single api data into csv file +with open('api_data.csv','w',newline="")as f: + writer=csv.writer(f) + writer.writerow(['Id','Title','Body','userId']) + writer.writerow([data['id'],data['title'],data['body'],data['userId']]) +print('Data stored in a csv file.') From 179c1015af3a29da10dc191df24dc82149c07686 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 10 Mar 2026 21:48:34 +0530 Subject: [PATCH 095/132] Create simple API call.py --- Unit_4/APL Integration/simple API call.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Unit_4/APL Integration/simple API call.py diff --git a/Unit_4/APL Integration/simple API call.py b/Unit_4/APL Integration/simple API call.py new file mode 100644 index 0000000..196f281 --- /dev/null +++ b/Unit_4/APL Integration/simple API call.py @@ -0,0 +1,20 @@ +import requests as r + +response = r.get('https://dummyjson.com/posts/150') +print(type(response), response) + +# Check if the request was successful + +if response.status_code == 200: + print('Request Successful') +else: + print(f'Request failed with status code: {response.status_code}') + +# Check the response data +print(response.text) +print(type(response.text)) + +# Handle JSON responses +data = response.json() +print(f"Post Title: {data['title']}") +print(f"Post User: {data['userId']}") From f45327079a123f352ad85826d3a6687756d02da5 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 10 Mar 2026 21:49:13 +0530 Subject: [PATCH 096/132] Create Single API data into a JSON file.py --- .../Single API data into a JSON file.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Unit_4/APL Integration/Single API data into a JSON file.py diff --git a/Unit_4/APL Integration/Single API data into a JSON file.py b/Unit_4/APL Integration/Single API data into a JSON file.py new file mode 100644 index 0000000..6080289 --- /dev/null +++ b/Unit_4/APL Integration/Single API data into a JSON file.py @@ -0,0 +1,12 @@ +import requests as r +import json + +# Get the data from an API call +response = r.get("https://dummyjson.com/posts/149") +data = response.json() +print(data) + +# Save the data into a JSON file with formatting +with open('api_data.json', 'w') as f: + json.dump(data, f, indent = 4) +print('Data saved to file') From 786ad7917a3f888d2c79b2b849a648d629653703 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 10 Mar 2026 21:50:49 +0530 Subject: [PATCH 097/132] Add files via upload --- Exception Handling during API calls.py | 18 ++++++++++++++ Fetch API.py | 30 +++++++++++++++++++++++ Multiple API data into a JSON file.py | 30 +++++++++++++++++++++++ Request CSV.py | 21 ++++++++++++++++ Request XML.py | 33 ++++++++++++++++++++++++++ Save single API data into CSV File.py | 15 ++++++++++++ Simple API Call.py | 20 ++++++++++++++++ Single API data into a JSON file.py | 12 ++++++++++ 8 files changed, 179 insertions(+) create mode 100644 Exception Handling during API calls.py create mode 100644 Fetch API.py create mode 100644 Multiple API data into a JSON file.py create mode 100644 Request CSV.py create mode 100644 Request XML.py create mode 100644 Save single API data into CSV File.py create mode 100644 Simple API Call.py create mode 100644 Single API data into a JSON file.py diff --git a/Exception Handling during API calls.py b/Exception Handling during API calls.py new file mode 100644 index 0000000..2edc773 --- /dev/null +++ b/Exception Handling during API calls.py @@ -0,0 +1,18 @@ +import requests as req + +try: + response = req.get('https://dummyjson.com/posts/2400') + response.raise_for_status() + # Raise an exception for 4**, 5** errors + data = response.json() + print(f'Retrived {len(data)} records') +except req.exceptions.HTTPError as e: + print(f'HTTP Error: {e}') +except req.exceptions.ConnectionError as e: + print(f'Connection Error: Check internet connection {e}') +except req.exceptions.Timeout as e: + print(f'Timeout Error: Took too long to respond {e}') +except req.exceptions.RequestException as e: + print(f'Error in making request {e}') +except ValueError: + print('Error in passing the JSN response') \ No newline at end of file diff --git a/Fetch API.py b/Fetch API.py new file mode 100644 index 0000000..52ef924 --- /dev/null +++ b/Fetch API.py @@ -0,0 +1,30 @@ +import requests as req +import xml.etree.cElementTree as et + +response = req.get('https://dummyjson.com/posts/120') + +if response.status_code == 200: + print('Request Successful') +else: + print(f'Request failed: {response.status_code}') + +print(type(response.text), response.text) + +data = response.json() +print(data) + +root = et.Element("post") + +id_el = et.SubElement(root, "id") +id_el.text = str(data["id"]) + +title_el = et.SubElement(root, "title") +title_el.text = str(data["title"]) + +user_el = et.SubElement(root, "userId") +user_el.text = str(data["userId"]) + +tree = et.ElementTree(root) +tree.write("api_data.xml", encoding="utf-8", xml_declaration=True) + +print("Data stored successfully.") diff --git a/Multiple API data into a JSON file.py b/Multiple API data into a JSON file.py new file mode 100644 index 0000000..0063114 --- /dev/null +++ b/Multiple API data into a JSON file.py @@ -0,0 +1,30 @@ +import requests as r +import json + +response = r.get("https://dummyjson.com/posts") + +# Convert the data into JSON object +data = response.json() +print(data) + +# ---------------------------- +# Save the data into JSON file +# ---------------------------- + +# Process data into individual records +posts_list = [] +for post in data['posts']: + posts_list.append({'id': post['id'], + 'title': post['title'], + 'body': post['body'], + 'userId': post['userId'], + 'reactions': post['reactions']} + ) +print() +print(posts_list) + +# Store the data into a JSON file +with open('api_data_1.json', 'w') as f: + json.dump(posts_list, f, indent = 4) +print('Data stored successfully!') + diff --git a/Request CSV.py b/Request CSV.py new file mode 100644 index 0000000..4f685b2 --- /dev/null +++ b/Request CSV.py @@ -0,0 +1,21 @@ +import requests as req +import csv + +response = req.get('https://dummyjson.com/posts') +data = response.json() + +posts = data['posts'] + +with open('api_data_1.csv', 'w', newline='', encoding='utf-8') as f: + writer = csv.writer(f) + writer.writerow(['Id', 'Title', 'UserId', 'Views']) + + for p in posts: + writer.writerow([ + p['id'], + p['title'], + p['userId'], + p['views'] + ]) + +print('Data written successfully!!') diff --git a/Request XML.py b/Request XML.py new file mode 100644 index 0000000..1fa96fb --- /dev/null +++ b/Request XML.py @@ -0,0 +1,33 @@ +import requests as req +import xml.etree.ElementTree as ET + +response = req.get('https://dummyjson.com/posts') +data = response.json() + +root = ET.Element('posts') + +for item in data['posts']: + p_el = ET.SubElement(root, "post") + + id_el = ET.SubElement(p_el, "Id") + id_el.text = str(item["id"]) + + t_el = ET.SubElement(p_el, "Title") + t_el.text = str(item["title"]) + + u_el = ET.SubElement(p_el, "UserId") + u_el.text = str(item["userId"]) + + v_el = ET.SubElement(p_el, "Views") + v_el.text = str(item["views"]) + +# Create ElementTree AFTER the loop +tree = ET.ElementTree(root) + +tree.write( + 'api_data_1.xml', + encoding='utf-8', + xml_declaration=True +) + +print('Data stored successfully') diff --git a/Save single API data into CSV File.py b/Save single API data into CSV File.py new file mode 100644 index 0000000..4283c6f --- /dev/null +++ b/Save single API data into CSV File.py @@ -0,0 +1,15 @@ +import requests as r +import json +import csv + +response = r.get("https://dummyjson.com/posts/149") + +# Convert the data into JSON object +data = response.json() + +#save single api data into csv file +with open('api_data.csv','w',newline="")as f: + writer=csv.writer(f) + writer.writerow(['Id','Title','Body','userId']) + writer.writerow([data['id'],data['title'],data['body'],data['userId']]) +print('Data stored in a csv file.') \ No newline at end of file diff --git a/Simple API Call.py b/Simple API Call.py new file mode 100644 index 0000000..2c8023f --- /dev/null +++ b/Simple API Call.py @@ -0,0 +1,20 @@ +import requests as r + +response = r.get('https://dummyjson.com/posts/150') +print(type(response), response) + +# Check if the request was successful + +if response.status_code == 200: + print('Request Successful') +else: + print(f'Request failed with status code: {response.status_code}') + +# Check the response data +print(response.text) +print(type(response.text)) + +# Handle JSON responses +data = response.json() +print(f"Post Title: {data['title']}") +print(f"Post User: {data['userId']}") diff --git a/Single API data into a JSON file.py b/Single API data into a JSON file.py new file mode 100644 index 0000000..c639db0 --- /dev/null +++ b/Single API data into a JSON file.py @@ -0,0 +1,12 @@ +import requests as r +import json + +# Get the data from an API call +response = r.get("https://dummyjson.com/posts/149") +data = response.json() +print(data) + +# Save the data into a JSON file with formatting +with open('api_data.json', 'w') as f: + json.dump(data, f, indent = 4) +print('Data saved to file') From 572bb49863eca2b83085d6ee351f906a14aea07f Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 10 Mar 2026 21:51:04 +0530 Subject: [PATCH 098/132] Delete Exception Handling during API calls.py --- Exception Handling during API calls.py | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 Exception Handling during API calls.py diff --git a/Exception Handling during API calls.py b/Exception Handling during API calls.py deleted file mode 100644 index 2edc773..0000000 --- a/Exception Handling during API calls.py +++ /dev/null @@ -1,18 +0,0 @@ -import requests as req - -try: - response = req.get('https://dummyjson.com/posts/2400') - response.raise_for_status() - # Raise an exception for 4**, 5** errors - data = response.json() - print(f'Retrived {len(data)} records') -except req.exceptions.HTTPError as e: - print(f'HTTP Error: {e}') -except req.exceptions.ConnectionError as e: - print(f'Connection Error: Check internet connection {e}') -except req.exceptions.Timeout as e: - print(f'Timeout Error: Took too long to respond {e}') -except req.exceptions.RequestException as e: - print(f'Error in making request {e}') -except ValueError: - print('Error in passing the JSN response') \ No newline at end of file From cada6cecdba83bf8f48c28c4be6397a228dad46d Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 10 Mar 2026 21:51:16 +0530 Subject: [PATCH 099/132] Delete Fetch API.py --- Fetch API.py | 30 ------------------------------ 1 file changed, 30 deletions(-) delete mode 100644 Fetch API.py diff --git a/Fetch API.py b/Fetch API.py deleted file mode 100644 index 52ef924..0000000 --- a/Fetch API.py +++ /dev/null @@ -1,30 +0,0 @@ -import requests as req -import xml.etree.cElementTree as et - -response = req.get('https://dummyjson.com/posts/120') - -if response.status_code == 200: - print('Request Successful') -else: - print(f'Request failed: {response.status_code}') - -print(type(response.text), response.text) - -data = response.json() -print(data) - -root = et.Element("post") - -id_el = et.SubElement(root, "id") -id_el.text = str(data["id"]) - -title_el = et.SubElement(root, "title") -title_el.text = str(data["title"]) - -user_el = et.SubElement(root, "userId") -user_el.text = str(data["userId"]) - -tree = et.ElementTree(root) -tree.write("api_data.xml", encoding="utf-8", xml_declaration=True) - -print("Data stored successfully.") From cd408307f54852c0a97b19630f3feb45f73dafb9 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 10 Mar 2026 21:51:29 +0530 Subject: [PATCH 100/132] Delete Multiple API data into a JSON file.py --- Multiple API data into a JSON file.py | 30 --------------------------- 1 file changed, 30 deletions(-) delete mode 100644 Multiple API data into a JSON file.py diff --git a/Multiple API data into a JSON file.py b/Multiple API data into a JSON file.py deleted file mode 100644 index 0063114..0000000 --- a/Multiple API data into a JSON file.py +++ /dev/null @@ -1,30 +0,0 @@ -import requests as r -import json - -response = r.get("https://dummyjson.com/posts") - -# Convert the data into JSON object -data = response.json() -print(data) - -# ---------------------------- -# Save the data into JSON file -# ---------------------------- - -# Process data into individual records -posts_list = [] -for post in data['posts']: - posts_list.append({'id': post['id'], - 'title': post['title'], - 'body': post['body'], - 'userId': post['userId'], - 'reactions': post['reactions']} - ) -print() -print(posts_list) - -# Store the data into a JSON file -with open('api_data_1.json', 'w') as f: - json.dump(posts_list, f, indent = 4) -print('Data stored successfully!') - From 0764d23ff1b147740be6285b2719b4a9f16c8f69 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 10 Mar 2026 21:51:42 +0530 Subject: [PATCH 101/132] Delete Request CSV.py --- Request CSV.py | 21 --------------------- 1 file changed, 21 deletions(-) delete mode 100644 Request CSV.py diff --git a/Request CSV.py b/Request CSV.py deleted file mode 100644 index 4f685b2..0000000 --- a/Request CSV.py +++ /dev/null @@ -1,21 +0,0 @@ -import requests as req -import csv - -response = req.get('https://dummyjson.com/posts') -data = response.json() - -posts = data['posts'] - -with open('api_data_1.csv', 'w', newline='', encoding='utf-8') as f: - writer = csv.writer(f) - writer.writerow(['Id', 'Title', 'UserId', 'Views']) - - for p in posts: - writer.writerow([ - p['id'], - p['title'], - p['userId'], - p['views'] - ]) - -print('Data written successfully!!') From 713f8efa75a04236746c631249ba6b4e71810cdd Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 10 Mar 2026 21:51:52 +0530 Subject: [PATCH 102/132] Delete Request XML.py --- Request XML.py | 33 --------------------------------- 1 file changed, 33 deletions(-) delete mode 100644 Request XML.py diff --git a/Request XML.py b/Request XML.py deleted file mode 100644 index 1fa96fb..0000000 --- a/Request XML.py +++ /dev/null @@ -1,33 +0,0 @@ -import requests as req -import xml.etree.ElementTree as ET - -response = req.get('https://dummyjson.com/posts') -data = response.json() - -root = ET.Element('posts') - -for item in data['posts']: - p_el = ET.SubElement(root, "post") - - id_el = ET.SubElement(p_el, "Id") - id_el.text = str(item["id"]) - - t_el = ET.SubElement(p_el, "Title") - t_el.text = str(item["title"]) - - u_el = ET.SubElement(p_el, "UserId") - u_el.text = str(item["userId"]) - - v_el = ET.SubElement(p_el, "Views") - v_el.text = str(item["views"]) - -# Create ElementTree AFTER the loop -tree = ET.ElementTree(root) - -tree.write( - 'api_data_1.xml', - encoding='utf-8', - xml_declaration=True -) - -print('Data stored successfully') From f3e311824e81e2fbb3e947ed806f54755641b2af Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 10 Mar 2026 21:52:02 +0530 Subject: [PATCH 103/132] Delete Save single API data into CSV File.py --- Save single API data into CSV File.py | 15 --------------- 1 file changed, 15 deletions(-) delete mode 100644 Save single API data into CSV File.py diff --git a/Save single API data into CSV File.py b/Save single API data into CSV File.py deleted file mode 100644 index 4283c6f..0000000 --- a/Save single API data into CSV File.py +++ /dev/null @@ -1,15 +0,0 @@ -import requests as r -import json -import csv - -response = r.get("https://dummyjson.com/posts/149") - -# Convert the data into JSON object -data = response.json() - -#save single api data into csv file -with open('api_data.csv','w',newline="")as f: - writer=csv.writer(f) - writer.writerow(['Id','Title','Body','userId']) - writer.writerow([data['id'],data['title'],data['body'],data['userId']]) -print('Data stored in a csv file.') \ No newline at end of file From 200003d7d434f6cbb96bb30962114b911547845c Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 10 Mar 2026 21:52:12 +0530 Subject: [PATCH 104/132] Delete Simple API Call.py --- Simple API Call.py | 20 -------------------- 1 file changed, 20 deletions(-) delete mode 100644 Simple API Call.py diff --git a/Simple API Call.py b/Simple API Call.py deleted file mode 100644 index 2c8023f..0000000 --- a/Simple API Call.py +++ /dev/null @@ -1,20 +0,0 @@ -import requests as r - -response = r.get('https://dummyjson.com/posts/150') -print(type(response), response) - -# Check if the request was successful - -if response.status_code == 200: - print('Request Successful') -else: - print(f'Request failed with status code: {response.status_code}') - -# Check the response data -print(response.text) -print(type(response.text)) - -# Handle JSON responses -data = response.json() -print(f"Post Title: {data['title']}") -print(f"Post User: {data['userId']}") From 68476387fdd92ba1b91c79d3f8bea68dc53363a7 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 10 Mar 2026 21:52:22 +0530 Subject: [PATCH 105/132] Delete Single API data into a JSON file.py --- Single API data into a JSON file.py | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100644 Single API data into a JSON file.py diff --git a/Single API data into a JSON file.py b/Single API data into a JSON file.py deleted file mode 100644 index c639db0..0000000 --- a/Single API data into a JSON file.py +++ /dev/null @@ -1,12 +0,0 @@ -import requests as r -import json - -# Get the data from an API call -response = r.get("https://dummyjson.com/posts/149") -data = response.json() -print(data) - -# Save the data into a JSON file with formatting -with open('api_data.json', 'w') as f: - json.dump(data, f, indent = 4) -print('Data saved to file') From 18df8324d90d50e63fd151c0fcb8e30fbb5da970 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 12 Mar 2026 19:51:52 +0530 Subject: [PATCH 106/132] Create asyncio_1.py --- Unit_4/APL Integration/Async/asyncio_1.py | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 Unit_4/APL Integration/Async/asyncio_1.py diff --git a/Unit_4/APL Integration/Async/asyncio_1.py b/Unit_4/APL Integration/Async/asyncio_1.py new file mode 100644 index 0000000..6c25061 --- /dev/null +++ b/Unit_4/APL Integration/Async/asyncio_1.py @@ -0,0 +1,2 @@ +import asyncio +import time From 4ff532185c203b6f0d6abef9a3a53535df1345d9 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 12 Mar 2026 19:52:30 +0530 Subject: [PATCH 107/132] Update asyncio_1.py --- Unit_4/APL Integration/Async/asyncio_1.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Unit_4/APL Integration/Async/asyncio_1.py b/Unit_4/APL Integration/Async/asyncio_1.py index 6c25061..3bc995a 100644 --- a/Unit_4/APL Integration/Async/asyncio_1.py +++ b/Unit_4/APL Integration/Async/asyncio_1.py @@ -1,2 +1,11 @@ import asyncio import time +''' Define a coroutine''' +async def Task(name, delay): + print(f"Task {name} started execution at {time.strftime('%H:%M:%S')}") + await asyncio.sleep(10) + ''' Coroutine is paused for 10 seconds + Control is returned to the event loop during the delay''' + end_t = time.strftime('%H:%M:%S') + print(f'Task {name} completed execution at {end_t}') + return name, end_t From 8d8fb1fbff097b8f31e0769d6e04054f0a2fd49d Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 12 Mar 2026 19:53:11 +0530 Subject: [PATCH 108/132] Update asyncio_1.py --- Unit_4/APL Integration/Async/asyncio_1.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Unit_4/APL Integration/Async/asyncio_1.py b/Unit_4/APL Integration/Async/asyncio_1.py index 3bc995a..ed5c306 100644 --- a/Unit_4/APL Integration/Async/asyncio_1.py +++ b/Unit_4/APL Integration/Async/asyncio_1.py @@ -9,3 +9,14 @@ async def Task(name, delay): end_t = time.strftime('%H:%M:%S') print(f'Task {name} completed execution at {end_t}') return name, end_t +'''Coroutine execution is coordinated here''' +async def main(): + results = await asyncio.gather( + Task('A', 3), + Task('B', 0.5), + Task('C', 2) + ) + print('Complete Summary Report') + for name, t in results: + print(f"Task {name} completed at {t:.2f} seconds") + asyncio.run(main()) From c696f0be6c668ebf1fee99d3a14820def0fe7791 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 12 Mar 2026 19:56:09 +0530 Subject: [PATCH 109/132] Create asyncio_2.py --- Unit_4/APL Integration/Async/asyncio_2.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Unit_4/APL Integration/Async/asyncio_2.py diff --git a/Unit_4/APL Integration/Async/asyncio_2.py b/Unit_4/APL Integration/Async/asyncio_2.py new file mode 100644 index 0000000..3d26180 --- /dev/null +++ b/Unit_4/APL Integration/Async/asyncio_2.py @@ -0,0 +1,11 @@ +import asyncio +import time + +async def Job(name, delay): + start = time.time() + print(f'Job {name} started') + await asyncio.sleep(delay) + end = time.time() + tt = round(end-start, 2) + print(f'Job {name} executed in {tt} seconds') + return name, tt From eba8edbc7623983a20b0f35d81331b38fcbb5034 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 12 Mar 2026 19:56:36 +0530 Subject: [PATCH 110/132] Update asyncio_2.py --- Unit_4/APL Integration/Async/asyncio_2.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Unit_4/APL Integration/Async/asyncio_2.py b/Unit_4/APL Integration/Async/asyncio_2.py index 3d26180..adbf652 100644 --- a/Unit_4/APL Integration/Async/asyncio_2.py +++ b/Unit_4/APL Integration/Async/asyncio_2.py @@ -9,3 +9,14 @@ async def Job(name, delay): tt = round(end-start, 2) print(f'Job {name} executed in {tt} seconds') return name, tt +async def main(): + t0 = time.time() + ''' Overall start time ''' + results = await asyncio.gather(Job(1, 12), Job(2, 3), Job(3, 1), Job(4, 2), Job(5, 5), Job(6, 2)) + t1 = time.time() + print(f'Overall time taken for execution is {t1 - t0} seconds') + print('Individual Task Time') + for name, taken in results: + print(f'Job {name} took {taken} seconds') + +asyncio.run(main()) From 91c4007ccd08bf9edff63088d7cf984a618946e8 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 12 Mar 2026 19:58:08 +0530 Subject: [PATCH 111/132] Create asyncio_3.py --- Unit_4/APL Integration/Async/asyncio_3.py | 24 +++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Unit_4/APL Integration/Async/asyncio_3.py diff --git a/Unit_4/APL Integration/Async/asyncio_3.py b/Unit_4/APL Integration/Async/asyncio_3.py new file mode 100644 index 0000000..9d29249 --- /dev/null +++ b/Unit_4/APL Integration/Async/asyncio_3.py @@ -0,0 +1,24 @@ +import asyncio , time , aiohttp + +''' Used for asynchronous HTTP Requests ''' + +URL = ['https://google.com', + 'https://example.com', + 'https://www.python.org', + 'https://httpbin.org', + ] + +async def fetch(session, url): + ''' One HTTP request per call ''' + start = time.time() + try: + async with session.get(url, timeout = 10) as resp: + ''' A GET request is sent to the URL + The coroutine waits for the response + Control is returned to the event loop during ''' + ''' Wait ''' + await resp.read() + ''' Read the full response body ''' + end = time.time() + taken = round(end-start, 2) + return url, resp.status, taken From 8fad5504e42d086e3ab94a0e9ca57c752a445bc0 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 12 Mar 2026 19:58:32 +0530 Subject: [PATCH 112/132] Update asyncio_3.py --- Unit_4/APL Integration/Async/asyncio_3.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Unit_4/APL Integration/Async/asyncio_3.py b/Unit_4/APL Integration/Async/asyncio_3.py index 9d29249..e29d7b4 100644 --- a/Unit_4/APL Integration/Async/asyncio_3.py +++ b/Unit_4/APL Integration/Async/asyncio_3.py @@ -22,3 +22,22 @@ async def fetch(session, url): end = time.time() taken = round(end-start, 2) return url, resp.status, taken + except Exception: + end = time.time() + taken = round(end - start, 2) + return url, -1, taken + ''' -1 represents a failure status''' + +async def main(): + async with aiohttp.ClientSession() as session: + ''' A single shared HTTP session is created ''' + ''' It is reused for all the HTTP requests ''' + results = await asyncio.gather(*(fetch(session, u) for u in URL)) + ''' All fetch coroutines are scheduled together ''' + ''' Execution waits until all requests are complete + Waiting time is shared by all requests ''' + + for url, status, taken in results: + print(f'URL {url} returned a status code {status} in {taken} seconds') + +asyncio.run(main()) From 4ca2062b012b09388cea207ac033b4daed0dbbcd Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 12 Mar 2026 19:59:16 +0530 Subject: [PATCH 113/132] Create asyncio_4.py --- Unit_4/APL Integration/Async/asyncio_4.py | 28 +++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Unit_4/APL Integration/Async/asyncio_4.py diff --git a/Unit_4/APL Integration/Async/asyncio_4.py b/Unit_4/APL Integration/Async/asyncio_4.py new file mode 100644 index 0000000..647670c --- /dev/null +++ b/Unit_4/APL Integration/Async/asyncio_4.py @@ -0,0 +1,28 @@ +import asyncio +import time + +# ------------------------------------------------- +# ASYNCHRONOUS IMPLEMENTATION +# ------------------------------------------------- + +async def square_async(n): + await asyncio.sleep(0.1) + return n * n + + +async def compute_squares_async(start, end): + tasks = [] + for i in range(start, end + 1): + tasks.append(square_async(i)) + return await asyncio.gather(*tasks) + + +async def run_async(start, end): + t0 = time.perf_counter() + results = await compute_squares_async(start, end) + t1 = time.perf_counter() + + for i, sq in enumerate(results, start): + print("Async square of", i, "is", sq) + + return round(t1 - t0, 2) From ad3c554399f4ae660fb2d8aa05ac9958d676bd2a Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 12 Mar 2026 19:59:40 +0530 Subject: [PATCH 114/132] Update asyncio_4.py --- Unit_4/APL Integration/Async/asyncio_4.py | 26 +++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Unit_4/APL Integration/Async/asyncio_4.py b/Unit_4/APL Integration/Async/asyncio_4.py index 647670c..5a2afa1 100644 --- a/Unit_4/APL Integration/Async/asyncio_4.py +++ b/Unit_4/APL Integration/Async/asyncio_4.py @@ -26,3 +26,29 @@ async def run_async(start, end): print("Async square of", i, "is", sq) return round(t1 - t0, 2) + +# ------------------------------------------------- +# SYNCHRONOUS IMPLEMENTATION +# ------------------------------------------------- + +def square_sync(n): + time.sleep(0.1) + return n * n + + +def compute_squares_sync(start, end): + results = [] + for i in range(start, end + 1): + results.append(square_sync(i)) + return results + + +def run_sync(start, end): + t0 = time.perf_counter() + results = compute_squares_sync(start, end) + t1 = time.perf_counter() + + for i, sq in enumerate(results, start): + print("Sync square of", i, "is", sq) + + return round(t1 - t0, 2) From 2a18812cfc80e548799b535da27cc3cadb3aafa5 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 12 Mar 2026 20:00:25 +0530 Subject: [PATCH 115/132] Update asyncio_4.py --- Unit_4/APL Integration/Async/asyncio_4.py | 37 +++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/Unit_4/APL Integration/Async/asyncio_4.py b/Unit_4/APL Integration/Async/asyncio_4.py index 5a2afa1..440050b 100644 --- a/Unit_4/APL Integration/Async/asyncio_4.py +++ b/Unit_4/APL Integration/Async/asyncio_4.py @@ -52,3 +52,40 @@ def run_sync(start, end): print("Sync square of", i, "is", sq) return round(t1 - t0, 2) + +# ------------------------------------------------- +# USER INPUT +# ------------------------------------------------- + +start = int(input("Enter the starting value: ")) +end = int(input("Enter the ending value: ")) + + +# ------------------------------------------------- +# RUN ASYNC +# ------------------------------------------------- + +print("\nRunning asynchronous program") +async_time = asyncio.run(run_async(start, end)) +print(f"Asynchronous total time {async_time} seconds\n") + + +# ------------------------------------------------- +# RUN SYNC +# ------------------------------------------------- + +print("Running synchronous program") +sync_time = run_sync(start, end) +print(f"Synchronous total time {sync_time} seconds\n") + + +# ------------------------------------------------- +# TIME COMPARISON +# ------------------------------------------------- + +print("Time difference") + +if sync_time > async_time: + print(f"Asynchronous was faster by {round(sync_time - async_time, 2)} seconds") +else: + print(f"Synchronous was faster by {round(async_time - sync_time, 2)} seconds") From bc6fb57e0cab0ba62ae2cfcf0fc29a157ca3de97 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Thu, 12 Mar 2026 20:01:01 +0530 Subject: [PATCH 116/132] Create Square of number Using async.py --- .../Async/Square of number Using async.py | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Unit_4/APL Integration/Async/Square of number Using async.py diff --git a/Unit_4/APL Integration/Async/Square of number Using async.py b/Unit_4/APL Integration/Async/Square of number Using async.py new file mode 100644 index 0000000..6acd91d --- /dev/null +++ b/Unit_4/APL Integration/Async/Square of number Using async.py @@ -0,0 +1,25 @@ +''' Program to implement both synchronous and asynchronous execution for calculating square of a range of numbers''' + +import asyncio, time + +async def square_async(n): + await asyncio.sleep(0.1) + return n*n + +async def compute_squares_async(start, end): + tasks = [] + for i in range(start, end+1): + tasks.append(square_async(i)) + return await asyncio.gather(*tasks) + +async def main_async(): + start = int(input("Enter the starting point: ")) + end = int(input("Enter the ending point: ")) + t0 = time.time() + results = await compute_squares_async(start, end) + t1 = time.time() + for i, sq in enumerate(results, start): + print(f'Async square of {i} is {sq}') + print(f'Async time of {round(t1 - t0, 2)}') + +asyncio.run(main_async()) From de1d86f60a0cb2006eccc16243f4cbb49aecb9e6 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 13 Mar 2026 16:44:49 +0530 Subject: [PATCH 117/132] Create Chatgpt static webpages.py --- .../Web Scrapping/Chatgpt static webpages.py | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Unit_4/APL Integration/Web Scrapping/Chatgpt static webpages.py diff --git a/Unit_4/APL Integration/Web Scrapping/Chatgpt static webpages.py b/Unit_4/APL Integration/Web Scrapping/Chatgpt static webpages.py new file mode 100644 index 0000000..2e33aa5 --- /dev/null +++ b/Unit_4/APL Integration/Web Scrapping/Chatgpt static webpages.py @@ -0,0 +1,67 @@ +from urllib.request import urlopen +from bs4 import BeautifulSoup as bs +import pandas as pd +import re +import matplotlib.pyplot as plt + +# Url which contains data +url="https://tatamumbaimarathon.procam.in/results/race-results" + +# pass url to urlopen() to get html of page +html=urlopen(url) +print(type(html),html) + +# construct BeautifulSoup obj using the html +soup=bs(html,'lxml') + +# Extract teh title of the Webpage +title=soup.title +print(title) +print(type(title)) + +# Extract the text of the webpage +text=soup.get_text() +print(soup.text,type(text)) +print("\n \n") +# print(text,type(text)) #both are same res + +# Extract the useful html tags within the page +soup.find_all('a') + +# Print the hyperlinks +all_links=soup.find_all('a') +for link in all_links: + print(link.get('href')) + +# Extract tabular data +rows=soup.find_all('tr') +print(rows) +print("\n") +print(type(rows)) + +# Get all table rows in a list form and convert into a DF +for row in rows: + row_td=row.find_all('td') +print(row_td) +print("\n\n") +print(type(row_td)) + +# Extract the data without the html tags +str_cell=str(row_td) +cleantext=bs(str_cell, 'lxml').get_text() +print(cleantext) +print("\n\n") +print(type(cleantext)) + +# Extract the Data without html tags using regex +list_row=[] +for row in rows: + cells=row.find_all('td') + str_cell=str(cells) + clean=re.compile('<.*?>') + clean_l=(re.sub(clean,'',str_cell)) + list_row.append(clean_l) + print(list_row) + +df=pd.DataFrame(list_row) +print(df.head(10)) From 6624b1b37d4f708241a24c28b53706df7983ac26 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 13 Mar 2026 16:45:20 +0530 Subject: [PATCH 118/132] Update Chatgpt static webpages.py --- .../Web Scrapping/Chatgpt static webpages.py | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/Unit_4/APL Integration/Web Scrapping/Chatgpt static webpages.py b/Unit_4/APL Integration/Web Scrapping/Chatgpt static webpages.py index 2e33aa5..38f32d2 100644 --- a/Unit_4/APL Integration/Web Scrapping/Chatgpt static webpages.py +++ b/Unit_4/APL Integration/Web Scrapping/Chatgpt static webpages.py @@ -65,3 +65,59 @@ df=pd.DataFrame(list_row) print(df.head(10)) + +# Data Manipulation and Cleaning +df1=df[0].str.split(',',expand=True) +print(df1.head(5)) + +# Remove the opening square braces +df1[0]=df1[0].str.strip('[') +print(df1.head(5)) + +df1[4]=df1[4].str.strip(']') +print(df1.head(5)) + +# Accessing the title for the cols +col_labels=soup.find_all('th') +print(col_labels) +print('\n\n') +print(type(col_labels)) +all_head=[] +col_str=str(col_labels) +clean_text=bs(col_str,'lxml').get_text() #Removes all the tags from the text +all_head.append(clean_text) +print(all_head) + +# convert to df +df2=pd.DataFrame(all_head) +print(df2) + +#splitting +df3=df2[0].str.split(',',expand=True) +print(df3.head(5)) + +# Remove the opening square braces +df3[0]=df3[0].str.strip('[') +df3[4]=df3[4].str.strip(']') +print(df3.head(5)) +print("\n\n") + +#--------MERGE THE TWO DF------------ +frames=[df3,df1] +df4=pd.concat(frames) +print(df4.head(5)) + +# -- Assign the 1st row to be the table header +df5=df4.rename(columns=df4.iloc[0]) +print(df5.head(5)) + +#---Drop all rows with missing vals +df5=df5.dropna(axis=0,how='any') +print(df5.head(5)) + +#---Drop row 0 +df5=df5.drop(index=0) +print(df5.head(5)) +print("\n") +df5.info() +print(df5.shape) From fa5d4810765f1d799528722f8e0154c95c36fb17 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 13 Mar 2026 16:45:44 +0530 Subject: [PATCH 119/132] Update Chatgpt static webpages.py --- .../Web Scrapping/Chatgpt static webpages.py | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/Unit_4/APL Integration/Web Scrapping/Chatgpt static webpages.py b/Unit_4/APL Integration/Web Scrapping/Chatgpt static webpages.py index 38f32d2..68e7519 100644 --- a/Unit_4/APL Integration/Web Scrapping/Chatgpt static webpages.py +++ b/Unit_4/APL Integration/Web Scrapping/Chatgpt static webpages.py @@ -121,3 +121,78 @@ print("\n") df5.info() print(df5.shape) + + +#____Processing of DF_________ + +#a. convert the finish time to total no of minutes. +df5.columns = df5.columns.str.strip().str.replace('\n',' ', regex=False) + +time_mins = [ + (int(h)*3600 + int(m)*60 + int(s)) / 60 + for h,m,s in (t.split(':') for t in df5['FINISH TIME']) +] + +# Convert Finish Time (HH:MM:SS) to total minutes + +#add the new col as run_mins +df5['Run_mins'] = time_mins + + +#a.--Get the mean time taken by each nationalty +df5.groupby('NATIONALITY')['Run_mins'].mean() + + +#b/---Find the no of runners per nationality +df5['NATIONALITY'].value_counts() + + +#c.---Get the difference of minutes between each runners +df5['Diff_mins'] = df5['Run_mins'].diff() + + +#d.Define the category of the runners based on the time taken +df5['CATEGORY']=pd.cut( + df5['Run_mins'], + bins=[0,120,140,160,200], + labels=['Elite','Strong','Moderate','Slow'] +) +print(df5) + +#____VISUALIZE THE DATA______ + +plt.hist(df5['Run_mins'],bins=10) +plt.xlabel('Minutes') +plt.ylabel('Frequency') +plt.show() + +#--create box plot for time duration +plt.boxplot(df5['Run_mins']) +plt.ylabel('Minutes') +plt.show() + +#create bargraphs for each nationality +nat_c=df5['NATIONALITY'].value_counts() +nat_c.plot(kind='bar') +df5.groupby('NATIONALITY')['Run_mins'].mean().plot(kind='bar') +plt.show() + + +#create scatter plots +plt.scatter(df5['RANK'],df5['Run_mins']) +plt.xlabel('RANK') +plt.ylabel('Finish time (mins)') +plt.show() + +#create horizontal bar graphs +top10=df5.nsmallest(10,'Run_mins') +plt.barh(top10['NATIONALITY'],top10['Run_mins']) +plt.show() + +top10=df5.nsmallest(10,'Run_mins') +plt.barh(top10['NAME'],top10['Run_mins']) +plt.show() + +#create line graphs +plt.plot(df5['Run_mins'].expanding().mean()) +plt.show() From 22898040d95cfc50f00e3cf265d9e19ebfa06174 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Fri, 13 Mar 2026 16:46:40 +0530 Subject: [PATCH 120/132] Create static webpages.py --- .../Web Scrapping/static webpages.py | 145 ++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 Unit_4/APL Integration/Web Scrapping/static webpages.py diff --git a/Unit_4/APL Integration/Web Scrapping/static webpages.py b/Unit_4/APL Integration/Web Scrapping/static webpages.py new file mode 100644 index 0000000..55e984b --- /dev/null +++ b/Unit_4/APL Integration/Web Scrapping/static webpages.py @@ -0,0 +1,145 @@ +from urllib.request import urlopen +from bs4 import BeautifulSoup as bs +import pandas as pd +import matplotlib.pyplot as plt + +# --------------------------------- +# URL +# --------------------------------- + +url = "https://tatamumbaimarathon.procam.in/results/race-results" +html = urlopen(url) +soup = bs(html, "lxml") + +# --------------------------------- +# Title +# --------------------------------- + +print(soup.title.text.strip()) + +# --------------------------------- +# Extract table +# NOTE: Page is JS-rendered, so this will usually return empty. +# Code is defensive and will not crash. +# --------------------------------- + +table = soup.find("table") + +if table is None: + print("No static table found. Page content is JavaScript-rendered.") + exit() + +# --------------------------------- +# Extract headers +# --------------------------------- + +headers = [th.get_text(strip=True) for th in table.find_all("th")] + +# --------------------------------- +# Extract rows +# --------------------------------- + +rows = [] +for tr in table.find_all("tr"): + cells = [td.get_text(strip=True) for td in tr.find_all("td")] + if cells: + rows.append(cells) + +# --------------------------------- +# Create DataFrame +# --------------------------------- + +df = pd.DataFrame(rows, columns=headers) +print(df.head()) + +# --------------------------------- +# Basic Cleaning +# --------------------------------- + +df.columns = df.columns.str.upper().str.replace("\n", " ", regex=False) +df = df.dropna(how="any") + +# --------------------------------- +# Convert FINISH TIME → minutes +# --------------------------------- + +def time_to_minutes(t): + try: + h, m, s = map(int, t.split(":")) + return (h * 3600 + m * 60 + s) / 60 + except: + return None + +if "FINISH TIME" in df.columns: + df["RUN_MINS"] = df["FINISH TIME"].apply(time_to_minutes) + df = df.dropna(subset=["RUN_MINS"]) +else: + print("FINISH TIME column not found.") + exit() + +print(df.head()) + +# --------------------------------- +# Visualization +# --------------------------------- + +plt.hist(df["RUN_MINS"], bins=10) +plt.xlabel("Minutes") +plt.ylabel("Frequency") +plt.title("Finish Time Distribution") +plt.show() + +plt.boxplot(df["RUN_MINS"]) +plt.ylabel("Minutes") +plt.title("Finish Time Boxplot") +plt.show() + +if "NATIONALITY" in df.columns: + df["NATIONALITY"].value_counts().plot(kind="bar") + plt.title("Runners by Nationality") + plt.show() + + df.groupby("NATIONALITY")["RUN_MINS"].mean().plot(kind="bar") + plt.title("Average Finish Time by Nationality") + plt.show() + +if "RANK" in df.columns: + plt.scatter(df["RANK"].astype(int), df["RUN_MINS"]) + plt.xlabel("Rank") + plt.ylabel("Finish Time (mins)") + plt.title("Rank vs Finish Time") + plt.show() + +top10 = df.nsmallest(10, "RUN_MINS") + +plt.barh(top10["NAME"], top10["RUN_MINS"]) +plt.xlabel("Minutes") +plt.title("Top 10 Fastest Runners") +plt.show() + +plt.plot(df["RUN_MINS"].expanding().mean()) +plt.title("Expanding Mean of Finish Time") +plt.ylabel("Minutes") +plt.show() + + +''' +This website cannot be scraped fully with BeautifulSoup alone +The results table is populated via JavaScript. Your original approach cannot work reliably. + +Correct tool for real data +If you actually need the results: + +selenium + +OR direct API calls (preferred) + +OR browser network inspection + +Regex-based HTML stripping is incorrect +BeautifulSoup already provides clean text safely. + +Your plotting depended on Run_mins, which never existed +This was a guaranteed runtime failure. + +''' From 2a1757ff0f11407363168cdc8875ba101ab871a0 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 17 Mar 2026 22:27:01 +0530 Subject: [PATCH 121/132] Create CRUD insert.py --- Unit_4/APL Integration/CRUD insert.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Unit_4/APL Integration/CRUD insert.py diff --git a/Unit_4/APL Integration/CRUD insert.py b/Unit_4/APL Integration/CRUD insert.py new file mode 100644 index 0000000..7b35548 --- /dev/null +++ b/Unit_4/APL Integration/CRUD insert.py @@ -0,0 +1,24 @@ +import psycopg2 as psy + +# Connect to the college Database +conn = psy.connect( + dbname = 'College', + user = 'postgres', + password = 'vaibhavhinduja', + host = 'localhost', + port = '5432' +) + +if conn: + print('Connection established successfully.') +else: + print('Connection to PostgreSQL encountered error.') + +cur = conn.cursor() +cur.execute("INSERT INTO students_1(srn, student_name, semester, section) VALUES(1001, 'Shannu', 'Sem 1', 'D')") +cur.execute("INSERT INTO students_1(srn, student_name, semester, section) VALUES(1002, 'Nypunya', 'Sem 1', 'E')") +cur.execute("INSERT INTO students_1(srn, student_name, semester, section) VALUES(1003, 'Hrithika', 'Sem 1', 'E')") +cur.execute("INSERT INTO students_1(srn, student_name, semester, section) VALUES(1004, 'ELECTRA', 'Sem 1', 'A')") +conn.commit() +cur.close() +conn.close() From b6bffb3d593c7f112706fea310c198ee9ce2bab5 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 17 Mar 2026 22:27:56 +0530 Subject: [PATCH 122/132] Create CURD read.py --- Unit_4/APL Integration/CURD read.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Unit_4/APL Integration/CURD read.py diff --git a/Unit_4/APL Integration/CURD read.py b/Unit_4/APL Integration/CURD read.py new file mode 100644 index 0000000..40e6b5d --- /dev/null +++ b/Unit_4/APL Integration/CURD read.py @@ -0,0 +1,10 @@ +import psycopg2 as psy + +# Connect to the college Database +conn = psy.connect( + dbname = 'College', + user = 'postgres', + password = 'vaibhavhinduja', + host = 'localhost', + port = '5432' +) From fe6794e5ddb393e3c9bf9f3807e90d7f4772d559 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 17 Mar 2026 22:28:11 +0530 Subject: [PATCH 123/132] Update CURD read.py --- Unit_4/APL Integration/CURD read.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Unit_4/APL Integration/CURD read.py b/Unit_4/APL Integration/CURD read.py index 40e6b5d..9b5f6e5 100644 --- a/Unit_4/APL Integration/CURD read.py +++ b/Unit_4/APL Integration/CURD read.py @@ -8,3 +8,18 @@ host = 'localhost', port = '5432' ) + +if conn: + print('Connection established successfully.') +else: + print('Connection to PostgreSQL encountered error.') + +cur = conn.cursor() +cur.execute("SELECT * FROM students_1") +rows = cur.fetchall() +conn.commit() +cur.close() +conn.close() + +for row in rows: + print(row) From 02b77309a1565e3af92908083fe212fa76af5f91 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 17 Mar 2026 22:29:27 +0530 Subject: [PATCH 124/132] Create CURD update.py --- Unit_4/APL Integration/CURD update.py | 29 +++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Unit_4/APL Integration/CURD update.py diff --git a/Unit_4/APL Integration/CURD update.py b/Unit_4/APL Integration/CURD update.py new file mode 100644 index 0000000..e12b7ba --- /dev/null +++ b/Unit_4/APL Integration/CURD update.py @@ -0,0 +1,29 @@ +import psycopg2 as psy + +# Connect to the college Database +conn = psy.connect( + dbname = 'College', + user = 'postgres', + password = 'vaibhavhinduja', + host = 'localhost', + port = '5432' +) + +if conn: + print('Connection established successfully.') +else: + print('Connection to PostgreSQL encountered error.') + +cur = conn.cursor() + +cur.execute(""" + UPDATE students_1 + SET student_name = 'Nypunya Sathish', + semester = 'Sem 1', + section = 'E' + WHERE srn = 1002 +""") + +conn.commit() +cur.close() +conn.close() From f59d5bb99e3aedb72253cb8cb2b92e4115a6ed7e Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 17 Mar 2026 22:30:09 +0530 Subject: [PATCH 125/132] Create Psycopg2 Database.py --- Unit_4/APL Integration/Psycopg2 Database.py | 34 +++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Unit_4/APL Integration/Psycopg2 Database.py diff --git a/Unit_4/APL Integration/Psycopg2 Database.py b/Unit_4/APL Integration/Psycopg2 Database.py new file mode 100644 index 0000000..28ba047 --- /dev/null +++ b/Unit_4/APL Integration/Psycopg2 Database.py @@ -0,0 +1,34 @@ +import psycopg2 as psy + +# Connect to the college Database +conn = psy.connect( + dbname = 'College', + user = 'postgres', + password = 'vaibhavhinduja', + host = 'localhost' +) + +if conn: + print('Connection established successfully.') +else: + print('Connection to PostgreSQL encountered error.') + +# ------------------ +# Create the cursor +# ------------------ + +cur = conn.cursor() # Opening the cursor + +# CRUD operation - Create the table +cur.execute( + """ + CREATE TABLE students_1( + srn SERIAL PRIMARY KEY, + student_name VARCHAR(80) NOT NULL, + semester VARCHAR(10) NOT NULL, + section VARCHAR(2) NOT NULL); + """ +) + +conn.commit() # Commit the changes +conn.close() # Close the connection From f6c3501349578a3dfbef5508a94c3007b34f594f Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 17 Mar 2026 22:30:56 +0530 Subject: [PATCH 126/132] Create SQL Alchemy.py --- Unit_4/APL Integration/SQL Alchemy.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Unit_4/APL Integration/SQL Alchemy.py diff --git a/Unit_4/APL Integration/SQL Alchemy.py b/Unit_4/APL Integration/SQL Alchemy.py new file mode 100644 index 0000000..635289e --- /dev/null +++ b/Unit_4/APL Integration/SQL Alchemy.py @@ -0,0 +1,25 @@ +import sqlalchemy as db + +# Create the connection to a particular database +engine = db.create_engine( + "postgresql://postgres:vaibhavhinduja@localhost:5432/College" +) +# First Value - DataBase software +# Second Value - Username +# Third Value - Password +# Fourth Value - Address of Database +# Fifth Value - Port Number +# Sixth Value - Name of the existing database + +print(engine) + +# Connect to the Database + +with engine.connect() as conn: + result = conn.execute(db.text("SELECT * FROM students_1")) + print(type(result)) + print(result) + print(result.fetchall()) + + for r in result.fetchall(): + print(r) From c8eead0309218eb881ec9f170b4a9b7df5301208 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 17 Mar 2026 22:32:06 +0530 Subject: [PATCH 127/132] Add files via upload --- all.pkl | Bin 0 -> 138 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 all.pkl diff --git a/all.pkl b/all.pkl new file mode 100644 index 0000000000000000000000000000000000000000..62a0abf917abddac4b80a626409326fc72c0d95b GIT binary patch literal 138 zcmZo*nd-#=0kKmwycxZjyqSAg6AKD*Qm23ffLw2u)E Date: Tue, 17 Mar 2026 22:32:29 +0530 Subject: [PATCH 128/132] Add files via upload --- api_data.csv | 1 + 1 file changed, 1 insertion(+) create mode 100644 api_data.csv diff --git a/api_data.csv b/api_data.csv new file mode 100644 index 0000000..e0b9351 --- /dev/null +++ b/api_data.csv @@ -0,0 +1 @@ +Id,Title,Body,userId From b912449d239d80bbf7ae572cea368a01c8a96750 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 17 Mar 2026 22:33:04 +0530 Subject: [PATCH 129/132] Add files via upload --- api_data.json | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 api_data.json diff --git a/api_data.json b/api_data.json new file mode 100644 index 0000000..176d508 --- /dev/null +++ b/api_data.json @@ -0,0 +1,16 @@ +{ + "id": 149, + "title": "During the first part of your life", + "body": "During the first part of your life, you only become aware of happiness once you have lost it. Then an age comes, a second one, in which you already know, at the moment when you begin to experience true happiness.", + "tags": [ + "love", + "american", + "classic" + ], + "reactions": { + "likes": 546, + "dislikes": 42 + }, + "views": 4638, + "userId": 56 +} \ No newline at end of file From 1d30ced71502e900ccf195730b710be9fe5d9322 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Tue, 17 Mar 2026 22:33:24 +0530 Subject: [PATCH 130/132] Add files via upload --- api_data.xml | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 api_data.xml diff --git a/api_data.xml b/api_data.xml new file mode 100644 index 0000000..4b2d935 --- /dev/null +++ b/api_data.xml @@ -0,0 +1,2 @@ + +120When a woman withdraws to give birth the105 \ No newline at end of file From c244ff4e11a88030e0d0c138e5cc4c70cca8b10e Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 22 Mar 2026 22:30:35 +0530 Subject: [PATCH 131/132] Rename AnonymousFunction.py to AnonymousFunction.py --- {unit_1 => Unit 1}/AnonymousFunction.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {unit_1 => Unit 1}/AnonymousFunction.py (100%) diff --git a/unit_1/AnonymousFunction.py b/Unit 1/AnonymousFunction.py similarity index 100% rename from unit_1/AnonymousFunction.py rename to Unit 1/AnonymousFunction.py From f9c30f070ab12a0600636891a5b44dc5f24f8ca6 Mon Sep 17 00:00:00 2001 From: Hemanth D C Date: Sun, 22 Mar 2026 22:31:32 +0530 Subject: [PATCH 132/132] Delete Unit 1 directory --- Unit 1/AnonymousFunction.py | 36 ------------------------------------ 1 file changed, 36 deletions(-) delete mode 100644 Unit 1/AnonymousFunction.py diff --git a/Unit 1/AnonymousFunction.py b/Unit 1/AnonymousFunction.py deleted file mode 100644 index 4ee4c0c..0000000 --- a/Unit 1/AnonymousFunction.py +++ /dev/null @@ -1,36 +0,0 @@ -from os import system -system("cls") - -# ---------- Anonymous Functions or Lambda Functions ---------- - -x = lambda a: a*a -print(type(x) ,id(x)) # 2452628238192 - -print(x(50)) # 2500 - -l = [1,4,5,6,78,98,98.0] -print(x(l[4])) # 6084 - -# Map() -b = list(map(x,l)) -c = list(map(lambda a: a*a, l)) -print(c) # [1, 16, 25, 36, 6084, 9604, 9604.0] -print(b) # [1, 16, 25, 36, 6084, 9604, 9604.0] - -d = list(map(len, ['apple','banana','cherry','durian','enterprise','fig'])) -print(d) # [5, 6, 6, 6, 10, 3] - -def square(x): - return x*x -sq = list(map(square, [1,2,3,4,5,6,7,8,9,10])) -print(sq) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] - -s_upper = list(map(str.upper, ['albus','peach','mercury','sisya'])) -print(s_upper) # ['ALBUS', 'PEACH', 'MERCURY', 'SISYA'] - -# ---------- Lambda Functions -# Condition based - -is_even = lambda x: x%2 == 0 -print(is_even(10)) # True -print(is_even(11)) # False