๐ PYTHON โ DAY 13 STUDY MATERIAL
โจ Topic: Strings in Python
โโโโโโโโโโโโโโโโโโโ
๐ What is a String?
A string is a sequence of characters enclosed in single (' ') or double (" ") quotes.
Example:
name = "Python"
msg = 'Hello'
โโโโโโโโโโโโโโโโโโโ
๐ข String Indexing
Each character in a string has an index number, starting from 0.
Example:
text = "Python"
text[0] โ P
text[1] โ y
text[-1] โ n
โโโโโโโโโโโโโโโโโโโ
โ๏ธ String Slicing
Used to extract a portion of a string.
Syntax:
string[start:end]
Example:
text = "Python"
print(text[0:3]) # Pyt
print(text[2:]) # thon
print(text[:4]) # Pyth
โโโโโโโโโโโโโโโโโโ
๐ String Looping
Example:
for ch in "Python":
print(ch)
โโโโโโโโโโโโโโโโโโโ
๐งฎ String Length
Use len() to find string length.
Example:
text = "Python"
print(len(text))
โโโโโโโโโโโโโโโโโโโ
๐ Strings are Immutable
Strings cannot be changed once created.
Example:
text = "Python"
text[0] = 'J' โ Error
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 13
โ Print each character of a string
โ Reverse a string
โ Find length of a string
โ Extract substring
Example Program:
text = input("Enter a string: ")
print(text[::-1])
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 13 Goal
โ Understand string basics
โ Use indexing and slicing confidently
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 14
๐ฅ String Methods
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
โจ Topic: Strings in Python
โโโโโโโโโโโโโโโโโโโ
๐ What is a String?
A string is a sequence of characters enclosed in single (' ') or double (" ") quotes.
Example:
name = "Python"
msg = 'Hello'
โโโโโโโโโโโโโโโโโโโ
๐ข String Indexing
Each character in a string has an index number, starting from 0.
Example:
text = "Python"
text[0] โ P
text[1] โ y
text[-1] โ n
โโโโโโโโโโโโโโโโโโโ
โ๏ธ String Slicing
Used to extract a portion of a string.
Syntax:
string[start:end]
Example:
text = "Python"
print(text[0:3]) # Pyt
print(text[2:]) # thon
print(text[:4]) # Pyth
โโโโโโโโโโโโโโโโโโ
๐ String Looping
Example:
for ch in "Python":
print(ch)
โโโโโโโโโโโโโโโโโโโ
๐งฎ String Length
Use len() to find string length.
Example:
text = "Python"
print(len(text))
โโโโโโโโโโโโโโโโโโโ
๐ Strings are Immutable
Strings cannot be changed once created.
Example:
text = "Python"
text[0] = 'J' โ Error
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 13
โ Print each character of a string
โ Reverse a string
โ Find length of a string
โ Extract substring
Example Program:
text = input("Enter a string: ")
print(text[::-1])
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 13 Goal
โ Understand string basics
โ Use indexing and slicing confidently
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 14
๐ฅ String Methods
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
๐ PYTHON โ DAY 14 STUDY MATERIAL
โจ Topic: String Methods in Python
โโโโโโโโโโโโโโโโโโโ
๐ What are String Methods?
String methods are built-in functions used to manipulate and format strings.
โโโโโโโโโโโโโโโโโโโ
๐ค Common String Methods
๐น upper() โ Converts string to uppercase
Example:
text = "python"
print(text.upper())
๐น lower() โ Converts string to lowercase
print(text.lower())
๐น title() โ Capitalizes first letter of each word
print("hello world".title())
๐น capitalize() โ Capitalizes first character
print("python".capitalize())
โโโโโโโโโโโโโโโโโโโ
โ๏ธ Trim Methods
๐น strip() โ Removes spaces from both sides
๐น lstrip() โ Removes left spaces
๐น rstrip() โ Removes right spaces
Example:
text = " python "
print(text.strip())
โโโโโโโโโโโโโโโโโโโ
๐ Replace & Split
๐น replace() โ Replaces part of string
print("hello python".replace("python", "world"))
๐น split() โ Splits string into list
print("a,b,c".split(","))
โโโโโโโโโโโโโโโโโโโ
๐ Search Methods
๐น find() โ Returns index of substring
print("python".find("t"))
๐น count() โ Counts occurrences
print("banana".count("a"))
โโโโโโโโโโโโโโโโโโโ
โ Check Methods
๐น isalpha() โ Checks alphabets
๐น isdigit() โ Checks digits
๐น isalnum() โ Checks alphanumeric
Example:
print("Python123".isalnum())
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 14
โ Convert string to uppercase
โ Count vowels in string
โ Replace a word in sentence
โ Split full name into first and last name
Example Program:
text = input("Enter text: ")
print(text.upper())
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 14 Goal
โ Master common string methods
โ Manipulate strings effectively
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 15
๐ฅ Lists in Python
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
โจ Topic: String Methods in Python
โโโโโโโโโโโโโโโโโโโ
๐ What are String Methods?
String methods are built-in functions used to manipulate and format strings.
โโโโโโโโโโโโโโโโโโโ
๐ค Common String Methods
๐น upper() โ Converts string to uppercase
Example:
text = "python"
print(text.upper())
๐น lower() โ Converts string to lowercase
print(text.lower())
๐น title() โ Capitalizes first letter of each word
print("hello world".title())
๐น capitalize() โ Capitalizes first character
print("python".capitalize())
โโโโโโโโโโโโโโโโโโโ
โ๏ธ Trim Methods
๐น strip() โ Removes spaces from both sides
๐น lstrip() โ Removes left spaces
๐น rstrip() โ Removes right spaces
Example:
text = " python "
print(text.strip())
โโโโโโโโโโโโโโโโโโโ
๐ Replace & Split
๐น replace() โ Replaces part of string
print("hello python".replace("python", "world"))
๐น split() โ Splits string into list
print("a,b,c".split(","))
โโโโโโโโโโโโโโโโโโโ
๐ Search Methods
๐น find() โ Returns index of substring
print("python".find("t"))
๐น count() โ Counts occurrences
print("banana".count("a"))
โโโโโโโโโโโโโโโโโโโ
โ Check Methods
๐น isalpha() โ Checks alphabets
๐น isdigit() โ Checks digits
๐น isalnum() โ Checks alphanumeric
Example:
print("Python123".isalnum())
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 14
โ Convert string to uppercase
โ Count vowels in string
โ Replace a word in sentence
โ Split full name into first and last name
Example Program:
text = input("Enter text: ")
print(text.upper())
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 14 Goal
โ Master common string methods
โ Manipulate strings effectively
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 15
๐ฅ Lists in Python
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
๐ PYTHON โ DAY 15 STUDY MATERIAL
โจ Topic: Lists in Python
โโโโโโโโโโโโโโโโโโโ
๐ What is a List?
A list is a collection of items stored in a single variable.
Lists are ordered, mutable (changeable) and allow duplicate values.
โโโโโโโโโโโโโโโโโโโ
๐น Creating a List
Example:
nums = [10, 20, 30, 40]
names = ["Python", "Java", "C"]
โโโโโโโโโโโโโโโโโโโ
๐ข List Indexing
Example:
nums = [10, 20, 30]
nums[0] โ 10
nums[-1] โ 30
โโโโโโโโโโโโโโโโโโโ
โ๏ธ List Slicing
Example:
nums = [1, 2, 3, 4, 5]
print(nums[1:4]) # [2, 3, 4]
โโโโโโโโโโโโโโโโโโโ
โ๏ธ Modify List Elements
Example:
nums = [10, 20, 30]
nums[1] = 25
print(nums)
โโโโโโโโโโโโโโโโโโโ
๐ Looping Through List
Example:
for n in nums:
print(n)
โโโโโโโโโโโโโโโโโโโ
๐งฎ List Length
Example:
print(len(nums))
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 15
โ Create a list of numbers
โ Access elements using index
โ Change list elements
โ Print all list elements using loop
Example Program:
nums = [5, 10, 15, 20]
for n in nums:
print(n)
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 15 Goal
โ Understand list basics
โ Use lists confidently
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 16
๐ฅ List Methods
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
โจ Topic: Lists in Python
โโโโโโโโโโโโโโโโโโโ
๐ What is a List?
A list is a collection of items stored in a single variable.
Lists are ordered, mutable (changeable) and allow duplicate values.
โโโโโโโโโโโโโโโโโโโ
๐น Creating a List
Example:
nums = [10, 20, 30, 40]
names = ["Python", "Java", "C"]
โโโโโโโโโโโโโโโโโโโ
๐ข List Indexing
Example:
nums = [10, 20, 30]
nums[0] โ 10
nums[-1] โ 30
โโโโโโโโโโโโโโโโโโโ
โ๏ธ List Slicing
Example:
nums = [1, 2, 3, 4, 5]
print(nums[1:4]) # [2, 3, 4]
โโโโโโโโโโโโโโโโโโโ
โ๏ธ Modify List Elements
Example:
nums = [10, 20, 30]
nums[1] = 25
print(nums)
โโโโโโโโโโโโโโโโโโโ
๐ Looping Through List
Example:
for n in nums:
print(n)
โโโโโโโโโโโโโโโโโโโ
๐งฎ List Length
Example:
print(len(nums))
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 15
โ Create a list of numbers
โ Access elements using index
โ Change list elements
โ Print all list elements using loop
Example Program:
nums = [5, 10, 15, 20]
for n in nums:
print(n)
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 15 Goal
โ Understand list basics
โ Use lists confidently
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 16
๐ฅ List Methods
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
๐ PYTHON โ DAY 16 STUDY MATERIAL
โจ Topic: List Methods in Python
โโโโโโโโโโโโโโโโโโโ
๐ What are List Methods?
List methods are built-in functions used to add, remove, and manage list elements.
โโโโโโโโโโโโโโโโโโโ
โ Adding Elements
๐น append() โ Adds element at the end
Example:
nums = [1, 2, 3]
nums.append(4)
๐น insert() โ Adds element at specific index
nums.insert(1, 10)
๐น extend() โ Adds multiple elements
nums.extend([5, 6])
โโโโโโโโโโโโโโโโโโโ
โ Removing Elements
๐น remove() โ Removes specific value
nums.remove(10)
๐น pop() โ Removes element by index
nums.pop()
nums.pop(1)
๐น clear() โ Removes all elements
nums.clear()
โโโโโโโโโโโโโโโโโโโ
๐ Other Useful List Methods
๐น sort() โ Sorts list
nums.sort()
๐น reverse() โ Reverses list
nums.reverse()
๐น count() โ Counts occurrence
nums.count(2)
๐น index() โ Returns index of value
nums.index(3)
โโโโโโโโโโโโโโโโโโโ
๐ง List Copy
๐น copy() โ Creates shallow copy
new_list = nums.copy()
โโโโโโโโโโโโโโโโโโโ
โ ๏ธ Important Notes
โข Lists are mutable
โข sort() changes original list
โข Use sorted() to keep original list
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 16
โ Add elements using append & insert
โ Remove elements using pop & remove
โ Sort a list
โ Reverse a list
Example Program:
nums = [4, 2, 1, 3]
nums.sort()
print(nums)
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 16 Goal
โ Master list operations
โ Manage list data efficiently
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 17
๐ฅ Tuples in Python
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
โจ Topic: List Methods in Python
โโโโโโโโโโโโโโโโโโโ
๐ What are List Methods?
List methods are built-in functions used to add, remove, and manage list elements.
โโโโโโโโโโโโโโโโโโโ
โ Adding Elements
๐น append() โ Adds element at the end
Example:
nums = [1, 2, 3]
nums.append(4)
๐น insert() โ Adds element at specific index
nums.insert(1, 10)
๐น extend() โ Adds multiple elements
nums.extend([5, 6])
โโโโโโโโโโโโโโโโโโโ
โ Removing Elements
๐น remove() โ Removes specific value
nums.remove(10)
๐น pop() โ Removes element by index
nums.pop()
nums.pop(1)
๐น clear() โ Removes all elements
nums.clear()
โโโโโโโโโโโโโโโโโโโ
๐ Other Useful List Methods
๐น sort() โ Sorts list
nums.sort()
๐น reverse() โ Reverses list
nums.reverse()
๐น count() โ Counts occurrence
nums.count(2)
๐น index() โ Returns index of value
nums.index(3)
โโโโโโโโโโโโโโโโโโโ
๐ง List Copy
๐น copy() โ Creates shallow copy
new_list = nums.copy()
โโโโโโโโโโโโโโโโโโโ
โ ๏ธ Important Notes
โข Lists are mutable
โข sort() changes original list
โข Use sorted() to keep original list
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 16
โ Add elements using append & insert
โ Remove elements using pop & remove
โ Sort a list
โ Reverse a list
Example Program:
nums = [4, 2, 1, 3]
nums.sort()
print(nums)
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 16 Goal
โ Master list operations
โ Manage list data efficiently
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 17
๐ฅ Tuples in Python
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
๐ PYTHON โ DAY 17 STUDY MATERIAL
โจ Topic: Tuples in Python
โโโโโโโโโโโโโโโโโโโ
๐ What is a Tuple?
A tuple is a collection of items stored in a single variable.
Tuples are ordered and immutable (cannot be changed).
โโโโโโโโโโโโโโโโโโโ
๐น Creating a Tuple
Example:
t = (10, 20, 30)
names = ("Python", "Java", "C")
Single element tuple:
x = (10,) โ comma is required
โโโโโโโโโโโโโโโโโโโ
๐ข Tuple Indexing
Example:
t = (10, 20, 30)
t[0] โ 10
t[-1] โ 30
โโโโโโโโโโโโโโโโโโโ
โ๏ธ Tuple Slicing
Example:
t = (1, 2, 3, 4, 5)
print(t[1:4])
โโโโโโโโโโโโโโโโโโโ
๐ Looping Through Tuple
Example:
for item in t:
print(item)
โโโโโโโโโโโโโโโโโโโ
๐ Tuple Immutability
Tuple elements cannot be modified.
Example:
t = (10, 20, 30)
t[0] = 5 โ Error
โโโโโโโโโโโโโโโโโโโ
๐งฎ Tuple Methods
๐น count() โ Counts occurrence
๐น index() โ Returns index
Example:
t = (1, 2, 2, 3)
print(t.count(2))
print(t.index(3))
โโโโโโโโโโโโโโโโโโโ
๐ Convert Tuple to List
Example:
t = (1, 2, 3)
lst = list(t)
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 17
โ Create tuple of numbers
โ Access elements using index
โ Loop through tuple
โ Convert tuple to list
Example Program:
t = (5, 10, 15)
for i in t:
print(i)
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 17 Goal
โ Understand tuple basics
โ Know difference between list & tuple
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 18
๐ฅ Sets in Python
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
โจ Topic: Tuples in Python
โโโโโโโโโโโโโโโโโโโ
๐ What is a Tuple?
A tuple is a collection of items stored in a single variable.
Tuples are ordered and immutable (cannot be changed).
โโโโโโโโโโโโโโโโโโโ
๐น Creating a Tuple
Example:
t = (10, 20, 30)
names = ("Python", "Java", "C")
Single element tuple:
x = (10,) โ comma is required
โโโโโโโโโโโโโโโโโโโ
๐ข Tuple Indexing
Example:
t = (10, 20, 30)
t[0] โ 10
t[-1] โ 30
โโโโโโโโโโโโโโโโโโโ
โ๏ธ Tuple Slicing
Example:
t = (1, 2, 3, 4, 5)
print(t[1:4])
โโโโโโโโโโโโโโโโโโโ
๐ Looping Through Tuple
Example:
for item in t:
print(item)
โโโโโโโโโโโโโโโโโโโ
๐ Tuple Immutability
Tuple elements cannot be modified.
Example:
t = (10, 20, 30)
t[0] = 5 โ Error
โโโโโโโโโโโโโโโโโโโ
๐งฎ Tuple Methods
๐น count() โ Counts occurrence
๐น index() โ Returns index
Example:
t = (1, 2, 2, 3)
print(t.count(2))
print(t.index(3))
โโโโโโโโโโโโโโโโโโโ
๐ Convert Tuple to List
Example:
t = (1, 2, 3)
lst = list(t)
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 17
โ Create tuple of numbers
โ Access elements using index
โ Loop through tuple
โ Convert tuple to list
Example Program:
t = (5, 10, 15)
for i in t:
print(i)
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 17 Goal
โ Understand tuple basics
โ Know difference between list & tuple
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 18
๐ฅ Sets in Python
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
๐ PYTHON โ DAY 18 STUDY MATERIAL
โจ Topic: Sets in Python
โโโโโโโโโโโโโโโโโโโ
๐ What is a Set?
A set is a collection of unique elements stored in a single variable.
Sets are unordered and do not allow duplicate values.
โโโโโโโโโโโโโโโโโโโ
๐น Creating a Set
Example:
s = {10, 20, 30}
names = {"Python", "Java", "C"}
Duplicate values are removed automatically:
s = {1, 2, 2, 3}
Output โ {1, 2, 3}
โโโโโโโโโโโโโโโโโโโ
โ Add Elements to Set
๐น add() โ Adds single element
s.add(40)
๐น update() โ Adds multiple elements
s.update([50, 60])
โโโโโโโโโโโโโโโโโโโ
โ Remove Elements from Set
๐น remove() โ Removes element (error if not found)
s.remove(20)
๐น discard() โ Removes element (no error)
s.discard(100)
๐น pop() โ Removes random element
s.pop()
โโโโโโโโโโโโโโโโโโโ
๐ Set Operations
๐น union() โ Combines sets
๐น intersection() โ Common elements
๐น difference() โ Remaining elements
Example:
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b))
print(a.intersection(b))
print(a.difference(b))
โโโโโโโโโโโโโโโโโโโ
๐งฎ Check Membership
Example:
print(2 in a)
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 18
โ Create a set
โ Add and remove elements
โ Perform union & intersection
โ Remove duplicate values from list using set
Example Program:
lst = [1, 2, 2, 3, 4]
s = set(lst)
print(s)
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 18 Goal
โ Understand set properties
โ Perform set operations
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 19
๐ฅ Dictionaries in Python
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
โจ Topic: Sets in Python
โโโโโโโโโโโโโโโโโโโ
๐ What is a Set?
A set is a collection of unique elements stored in a single variable.
Sets are unordered and do not allow duplicate values.
โโโโโโโโโโโโโโโโโโโ
๐น Creating a Set
Example:
s = {10, 20, 30}
names = {"Python", "Java", "C"}
Duplicate values are removed automatically:
s = {1, 2, 2, 3}
Output โ {1, 2, 3}
โโโโโโโโโโโโโโโโโโโ
โ Add Elements to Set
๐น add() โ Adds single element
s.add(40)
๐น update() โ Adds multiple elements
s.update([50, 60])
โโโโโโโโโโโโโโโโโโโ
โ Remove Elements from Set
๐น remove() โ Removes element (error if not found)
s.remove(20)
๐น discard() โ Removes element (no error)
s.discard(100)
๐น pop() โ Removes random element
s.pop()
โโโโโโโโโโโโโโโโโโโ
๐ Set Operations
๐น union() โ Combines sets
๐น intersection() โ Common elements
๐น difference() โ Remaining elements
Example:
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b))
print(a.intersection(b))
print(a.difference(b))
โโโโโโโโโโโโโโโโโโโ
๐งฎ Check Membership
Example:
print(2 in a)
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 18
โ Create a set
โ Add and remove elements
โ Perform union & intersection
โ Remove duplicate values from list using set
Example Program:
lst = [1, 2, 2, 3, 4]
s = set(lst)
print(s)
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 18 Goal
โ Understand set properties
โ Perform set operations
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 19
๐ฅ Dictionaries in Python
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
๐ PYTHON โ DAY 19 STUDY MATERIAL
โจ Topic: Dictionaries in Python
โโโโโโโโโโโโโโโโโโโ
๐ What is a Dictionary?
A dictionary stores data in keyโvalue pairs.
Dictionaries are unordered, mutable, and keys must be unique.
โโโโโโโโโโโโโโโโโโโ
๐น Creating a Dictionary
Example:
student = {
"name": "Soham",
"age": 20,
"course": "Python"
}
โโโโโโโโโโโโโโโโโโโ
๐ Access Dictionary Values
Example:
print(student["name"])
print(student.get("age"))
โโโโโโโโโโโโโโโโโโโ
โ๏ธ Modify Dictionary
Example:
student["age"] = 21
student["city"] = "Pune"
โโโโโโโโโโโโโโโโโโโ
โ Remove Dictionary Items
๐น pop() โ Removes specific key
student.pop("city")
๐น popitem() โ Removes last item
student.popitem()
๐น clear() โ Removes all items
student.clear()
โโโโโโโโโโโโโโโโโโโ
๐ Loop Through Dictionary
Example:
for key in student:
print(key, student[key])
โโโโโโโโโโโโโโโโโโโ
๐งฎ Dictionary Methods
๐น keys() โ Returns all keys
๐น values() โ Returns all values
๐น items() โ Returns key-value pairs
Example:
print(student.keys())
print(student.values())
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 19
โ Create student dictionary
โ Add and update values
โ Loop through dictionary
โ Delete a key
Example Program:
student = {"name": "Amit", "age": 22}
for k, v in student.items():
print(k, v)
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 19 Goal
โ Understand key-value storage
โ Use dictionaries effectively
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 20
๐ฅ Dictionary Methods & Nested Dictionary
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
โจ Topic: Dictionaries in Python
โโโโโโโโโโโโโโโโโโโ
๐ What is a Dictionary?
A dictionary stores data in keyโvalue pairs.
Dictionaries are unordered, mutable, and keys must be unique.
โโโโโโโโโโโโโโโโโโโ
๐น Creating a Dictionary
Example:
student = {
"name": "Soham",
"age": 20,
"course": "Python"
}
โโโโโโโโโโโโโโโโโโโ
๐ Access Dictionary Values
Example:
print(student["name"])
print(student.get("age"))
โโโโโโโโโโโโโโโโโโโ
โ๏ธ Modify Dictionary
Example:
student["age"] = 21
student["city"] = "Pune"
โโโโโโโโโโโโโโโโโโโ
โ Remove Dictionary Items
๐น pop() โ Removes specific key
student.pop("city")
๐น popitem() โ Removes last item
student.popitem()
๐น clear() โ Removes all items
student.clear()
โโโโโโโโโโโโโโโโโโโ
๐ Loop Through Dictionary
Example:
for key in student:
print(key, student[key])
โโโโโโโโโโโโโโโโโโโ
๐งฎ Dictionary Methods
๐น keys() โ Returns all keys
๐น values() โ Returns all values
๐น items() โ Returns key-value pairs
Example:
print(student.keys())
print(student.values())
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 19
โ Create student dictionary
โ Add and update values
โ Loop through dictionary
โ Delete a key
Example Program:
student = {"name": "Amit", "age": 22}
for k, v in student.items():
print(k, v)
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 19 Goal
โ Understand key-value storage
โ Use dictionaries effectively
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 20
๐ฅ Dictionary Methods & Nested Dictionary
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
๐ PYTHON โ DAY 20 STUDY MATERIAL
โจ Topic: Dictionary Methods & Nested Dictionary
โโโโโโโโโโโโโโโโโโ
๐ Important Dictionary Methods
๐น update() โ Adds or updates key-value pairs
Example:
student = {"name": "Soham"}
student.update({"age": 21})
๐น get() โ Returns value of key
print(student.get("name"))
๐น setdefault() โ Returns value, adds key if not present
student.setdefault("city", "Pune")
โโโโโโโโโโโโโโโโโโโ
โ Removing Dictionary Data
๐น del โ Deletes key
del student["age"]
๐น clear() โ Removes all data
student.clear()
โโโโโโโโโโโโโโโโโโโ
๐งฉ Nested Dictionary
A dictionary inside another dictionary is called a nested dictionary.
Example:
students = {
1: {"name": "Amit", "age": 20},
2: {"name": "Soham", "age": 21}
}
Access nested value:
print(students[1]["name"])
โโโโโโโโโโโโโโโโโโโ
๐ Loop Through Nested Dictionary
Example:
for id, info in students.items():
print(id, info["name"], info["age"])
โโโโโโโโโโโโโโโโโโโ
๐งฎ Copy Dictionary
๐น copy() โ Creates shallow copy
new_dict = student.copy()
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 20
โ Use update() and setdefault()
โ Create nested dictionary
โ Access and print nested values
โ Loop through nested dictionary
Example Program:
data = {1: {"name": "Raj", "marks": 80}}
print(data[1]["marks"])
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 20 Goal
โ Master dictionary methods
โ Work with nested dictionaries
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 21
๐ฅ Revision + Practice (Week Review)
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
โจ Topic: Dictionary Methods & Nested Dictionary
โโโโโโโโโโโโโโโโโโ
๐ Important Dictionary Methods
๐น update() โ Adds or updates key-value pairs
Example:
student = {"name": "Soham"}
student.update({"age": 21})
๐น get() โ Returns value of key
print(student.get("name"))
๐น setdefault() โ Returns value, adds key if not present
student.setdefault("city", "Pune")
โโโโโโโโโโโโโโโโโโโ
โ Removing Dictionary Data
๐น del โ Deletes key
del student["age"]
๐น clear() โ Removes all data
student.clear()
โโโโโโโโโโโโโโโโโโโ
๐งฉ Nested Dictionary
A dictionary inside another dictionary is called a nested dictionary.
Example:
students = {
1: {"name": "Amit", "age": 20},
2: {"name": "Soham", "age": 21}
}
Access nested value:
print(students[1]["name"])
โโโโโโโโโโโโโโโโโโโ
๐ Loop Through Nested Dictionary
Example:
for id, info in students.items():
print(id, info["name"], info["age"])
โโโโโโโโโโโโโโโโโโโ
๐งฎ Copy Dictionary
๐น copy() โ Creates shallow copy
new_dict = student.copy()
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 20
โ Use update() and setdefault()
โ Create nested dictionary
โ Access and print nested values
โ Loop through nested dictionary
Example Program:
data = {1: {"name": "Raj", "marks": 80}}
print(data[1]["marks"])
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 20 Goal
โ Master dictionary methods
โ Work with nested dictionaries
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 21
๐ฅ Revision + Practice (Week Review)
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
๐ PYTHON โ DAY 21 STUDY MATERIAL
โจ Topic: Revision + Practice (Week Review)
โโโโโโโโโโโโโโโโโโโ
๐ Topics Covered (Day 1 โ Day 20)
โ Python Introduction & Installation
โ Variables & Data Types
โ Operators
โ Conditional Statements
โ while Loop & for Loop
โ break, continue, pass
โ Pattern Programs
โ Functions & Arguments
โ Recursion
โ Strings & String Methods
โ Lists & List Methods
โ Tuples
โ Sets
โ Dictionaries & Nested Dictionary
โโโโโโโโโโโโโโโโโโโ
๐ง Quick Revision Points
๐น Variables are dynamically typed
๐น Indentation is mandatory in Python
๐น Lists are mutable, tuples are immutable
๐น Sets store unique values
๐น Dictionaries store key-value pairs
๐น Functions reduce code repetition
โโโโโโโโโโโโโโโโโโโ
๐งช Practice Programs โ Day 21
1๏ธโฃ Check whether a number is even or odd
num = int(input("Enter number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
โโโโโโโโโโโโโโโโโโโ
2๏ธโฃ Find sum of elements in a list
nums = [10, 20, 30]
print(sum(nums))
โโโโโโโโโโโโโโโโโโโ
3๏ธโฃ Reverse a string
text = input("Enter string: ")
print(text[::-1])
โโโโโโโโโโโโโโโโโโโ
4๏ธโฃ Count frequency using dictionary
text = "python"
freq = {}
for ch in text:
freq[ch] = freq.get(ch, 0) + 1
print(freq)
โโโโโโโโโโโโโโโโโโโ
โญ Challenge Tasks
โ Print star pyramid
โ Create simple calculator using functions
โ Remove duplicates from list
โ Store student data using dictionary
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 21 Goal
โ Revise all fundamentals
โ Identify weak topics
โ Build confidence in basics
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 22
๐ฅ File Handling in Python
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
โจ Topic: Revision + Practice (Week Review)
โโโโโโโโโโโโโโโโโโโ
๐ Topics Covered (Day 1 โ Day 20)
โ Python Introduction & Installation
โ Variables & Data Types
โ Operators
โ Conditional Statements
โ while Loop & for Loop
โ break, continue, pass
โ Pattern Programs
โ Functions & Arguments
โ Recursion
โ Strings & String Methods
โ Lists & List Methods
โ Tuples
โ Sets
โ Dictionaries & Nested Dictionary
โโโโโโโโโโโโโโโโโโโ
๐ง Quick Revision Points
๐น Variables are dynamically typed
๐น Indentation is mandatory in Python
๐น Lists are mutable, tuples are immutable
๐น Sets store unique values
๐น Dictionaries store key-value pairs
๐น Functions reduce code repetition
โโโโโโโโโโโโโโโโโโโ
๐งช Practice Programs โ Day 21
1๏ธโฃ Check whether a number is even or odd
num = int(input("Enter number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
โโโโโโโโโโโโโโโโโโโ
2๏ธโฃ Find sum of elements in a list
nums = [10, 20, 30]
print(sum(nums))
โโโโโโโโโโโโโโโโโโโ
3๏ธโฃ Reverse a string
text = input("Enter string: ")
print(text[::-1])
โโโโโโโโโโโโโโโโโโโ
4๏ธโฃ Count frequency using dictionary
text = "python"
freq = {}
for ch in text:
freq[ch] = freq.get(ch, 0) + 1
print(freq)
โโโโโโโโโโโโโโโโโโโ
โญ Challenge Tasks
โ Print star pyramid
โ Create simple calculator using functions
โ Remove duplicates from list
โ Store student data using dictionary
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 21 Goal
โ Revise all fundamentals
โ Identify weak topics
โ Build confidence in basics
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 22
๐ฅ File Handling in Python
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
๐ PYTHON โ DAY 22 STUDY MATERIAL
โจ Topic: File Handling in Python
โโโโโโโโโโโโโโโโโโโ
๐ What is File Handling?
File handling allows Python programs to read data from files and write data to files permanently.
โโโโโโโโโโโโโโโโโโโ
๐ Types of Files
โ Text files (.txt)
โ Binary files (.bin, .dat)
โโโโโโโโโโโโโโโโโโโ
๐ Opening a File
Syntax:
file = open("filename", "mode")
Common modes:
"r" โ Read
"w" โ Write
"a" โ Append
"x" โ Create
"rb" โ Read binary
"wb" โ Write binary
โโโโโโโโโโโโโโโโโโโ
๐ Reading from a File
Example:
file = open("data.txt", "r")
print(file.read())
file.close()
โโโโโโโโโโโโโโโโโโโ
โ๏ธ Writing to a File
Example:
file = open("data.txt", "w")
file.write("Hello Python")
file.close()
โโโโโโโโโโโโโโโโโโโ
โ Append Data to File
Example:
file = open("data.txt", "a")
file.write("\nWelcome")
file.close()
โโโโโโโโโโโโโโโโโโโ
๐ Using with Statement
Automatically closes the file.
Example:
with open("data.txt", "r") as file:
print(file.read())
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 22
โ Create a text file
โ Write data into file
โ Read file content
โ Append data to file
Example Program:
with open("test.txt", "w") as f:
f.write("Python File Handling")
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 22 Goal
โ Understand file operations
โ Read & write files safely
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 23
๐ฅ File Methods & File Modes
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
โจ Topic: File Handling in Python
โโโโโโโโโโโโโโโโโโโ
๐ What is File Handling?
File handling allows Python programs to read data from files and write data to files permanently.
โโโโโโโโโโโโโโโโโโโ
๐ Types of Files
โ Text files (.txt)
โ Binary files (.bin, .dat)
โโโโโโโโโโโโโโโโโโโ
๐ Opening a File
Syntax:
file = open("filename", "mode")
Common modes:
"r" โ Read
"w" โ Write
"a" โ Append
"x" โ Create
"rb" โ Read binary
"wb" โ Write binary
โโโโโโโโโโโโโโโโโโโ
๐ Reading from a File
Example:
file = open("data.txt", "r")
print(file.read())
file.close()
โโโโโโโโโโโโโโโโโโโ
โ๏ธ Writing to a File
Example:
file = open("data.txt", "w")
file.write("Hello Python")
file.close()
โโโโโโโโโโโโโโโโโโโ
โ Append Data to File
Example:
file = open("data.txt", "a")
file.write("\nWelcome")
file.close()
โโโโโโโโโโโโโโโโโโโ
๐ Using with Statement
Automatically closes the file.
Example:
with open("data.txt", "r") as file:
print(file.read())
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 22
โ Create a text file
โ Write data into file
โ Read file content
โ Append data to file
Example Program:
with open("test.txt", "w") as f:
f.write("Python File Handling")
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 22 Goal
โ Understand file operations
โ Read & write files safely
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 23
๐ฅ File Methods & File Modes
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
Forwarded from TECH BY WEB CODER
30 Pattern In Python.pdf
5 MB
Important Web Development And Programming Language Related Project๐
๐๐ป๐๐ป๐๐ป๐๐ป๐๐ป๐๐ป๐๐ป๐๐ป๐๐ป
Topic :- Top 30 Patterns in Python (Star, Alphabet, And Number)
๐๐ป๐๐ป๐๐ป๐๐ป๐๐ป๐๐ป๐๐ป๐๐ป๐๐ป
Topic :- Top 30 Patterns in Python (Star, Alphabet, And Number)
๐1
๐ PYTHON โ DAY 23 STUDY MATERIAL
โจ Topic: File Methods & File Modes
โโโโโโโโโโโโโโโโโโโ
๐ File Modes in Python
๐น "r" โ Read mode (file must exist)
๐น "w" โ Write mode (creates new / overwrites file)
๐น "a" โ Append mode (adds data at end)
๐น "x" โ Create file (error if file exists)
๐น "r+" โ Read + Write
๐น "w+" โ Write + Read
โโโโโโโโโโโโโโโโโโโ
๐ Important File Methods
๐น read() โ Reads entire file
๐น readline() โ Reads one line
๐น readlines() โ Reads all lines as list
Example:
with open("data.txt", "r") as f:
print(f.readline())
โโโโโโโโโโโโโโโโโโโ
โ๏ธ Writing Multiple Lines
Example:
with open("data.txt", "w") as f:
f.writelines(["Python\n", "Java\n", "C\n"])
โโโโโโโโโโโโโโโโโโโ
๐ File Cursor Position
๐น tell() โ Returns current position
๐น seek() โ Changes position
Example:
with open("data.txt", "r") as f:
print(f.tell())
f.seek(0)
โโโโโโโโโโโโโโโโโโโ
๐งน Closing a File
๐น close() โ Closes file manually
๐น with statement โ Closes automatically (recommended)
โโโโโโโโโโโโโโโโโโโ
โ ๏ธ Common File Errors
โ FileNotFoundError
โ PermissionError
โ Wrong mode usage
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 23
โ Read file line by line
โ Write multiple lines to file
โ Use tell() and seek()
โ Try different file modes
Example Program:
with open("demo.txt", "w+") as f:
f.write("Hello Python")
f.seek(0)
print(f.read())
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 23 Goal
โ Master file modes
โ Use file methods confidently
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 24
๐ฅ Exception Handling (try, except)
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
โจ Topic: File Methods & File Modes
โโโโโโโโโโโโโโโโโโโ
๐ File Modes in Python
๐น "r" โ Read mode (file must exist)
๐น "w" โ Write mode (creates new / overwrites file)
๐น "a" โ Append mode (adds data at end)
๐น "x" โ Create file (error if file exists)
๐น "r+" โ Read + Write
๐น "w+" โ Write + Read
โโโโโโโโโโโโโโโโโโโ
๐ Important File Methods
๐น read() โ Reads entire file
๐น readline() โ Reads one line
๐น readlines() โ Reads all lines as list
Example:
with open("data.txt", "r") as f:
print(f.readline())
โโโโโโโโโโโโโโโโโโโ
โ๏ธ Writing Multiple Lines
Example:
with open("data.txt", "w") as f:
f.writelines(["Python\n", "Java\n", "C\n"])
โโโโโโโโโโโโโโโโโโโ
๐ File Cursor Position
๐น tell() โ Returns current position
๐น seek() โ Changes position
Example:
with open("data.txt", "r") as f:
print(f.tell())
f.seek(0)
โโโโโโโโโโโโโโโโโโโ
๐งน Closing a File
๐น close() โ Closes file manually
๐น with statement โ Closes automatically (recommended)
โโโโโโโโโโโโโโโโโโโ
โ ๏ธ Common File Errors
โ FileNotFoundError
โ PermissionError
โ Wrong mode usage
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 23
โ Read file line by line
โ Write multiple lines to file
โ Use tell() and seek()
โ Try different file modes
Example Program:
with open("demo.txt", "w+") as f:
f.write("Hello Python")
f.seek(0)
print(f.read())
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 23 Goal
โ Master file modes
โ Use file methods confidently
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 24
๐ฅ Exception Handling (try, except)
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
๐ PYTHON โ DAY 24 STUDY MATERIAL
โจ Topic: Exception Handling in Python
โโโโโโโโโโโโโโโโโโโ
๐ What is an Exception?
An exception is an error that occurs during program execution, which interrupts normal flow.
Examples:
ZeroDivisionError
ValueError
TypeError
โโโโโโโโโโโโโโโโโโโ
๐ก Why Use Exception Handling?
โ Prevent program crash
โ Handle errors gracefully
โ Improve program reliability
โโโโโโโโโโโโโโโโโโโ
๐น try-except Block
Syntax:
try:
risky_code
except:
error_handling_code
Example:
try:
x = int(input("Enter number: "))
print(10 / x)
except:
print("Error occurred")
โโโโโโโโโโโโโโโโโโโ
๐น Handling Specific Exceptions
Example:
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero")
โโโโโโโโโโโโโโโโโโโ
๐น Multiple except Blocks
Example:
try:
x = int(input())
except ValueError:
print("Invalid input")
except ZeroDivisionError:
print("Division error")
โโโโโโโโโโโโโโโโโโโ
๐น else Block
Executes if no exception occurs.
Example:
try:
print(10 / 2)
except:
print("Error")
else:
print("Success")
โโโโโโโโโโโโโโโโโโโ
๐น finally Block
Always executes (used for cleanup).
Example:
try:
print(10 / 2)
finally:
print("Done")
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 24
โ Handle divide by zero
โ Handle invalid input
โ Use else and finally
โ Write safe calculator
Example Program:
try:
a = int(input("Enter a: "))
b = int(input("Enter b: "))
print(a / b)
except Exception as e:
print("Error:", e)
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 24 Goal
โ Handle runtime errors
โ Write crash-free programs
โโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 25
๐ฅ User-Defined Exceptions
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
โจ Topic: Exception Handling in Python
โโโโโโโโโโโโโโโโโโโ
๐ What is an Exception?
An exception is an error that occurs during program execution, which interrupts normal flow.
Examples:
ZeroDivisionError
ValueError
TypeError
โโโโโโโโโโโโโโโโโโโ
๐ก Why Use Exception Handling?
โ Prevent program crash
โ Handle errors gracefully
โ Improve program reliability
โโโโโโโโโโโโโโโโโโโ
๐น try-except Block
Syntax:
try:
risky_code
except:
error_handling_code
Example:
try:
x = int(input("Enter number: "))
print(10 / x)
except:
print("Error occurred")
โโโโโโโโโโโโโโโโโโโ
๐น Handling Specific Exceptions
Example:
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero")
โโโโโโโโโโโโโโโโโโโ
๐น Multiple except Blocks
Example:
try:
x = int(input())
except ValueError:
print("Invalid input")
except ZeroDivisionError:
print("Division error")
โโโโโโโโโโโโโโโโโโโ
๐น else Block
Executes if no exception occurs.
Example:
try:
print(10 / 2)
except:
print("Error")
else:
print("Success")
โโโโโโโโโโโโโโโโโโโ
๐น finally Block
Always executes (used for cleanup).
Example:
try:
print(10 / 2)
finally:
print("Done")
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 24
โ Handle divide by zero
โ Handle invalid input
โ Use else and finally
โ Write safe calculator
Example Program:
try:
a = int(input("Enter a: "))
b = int(input("Enter b: "))
print(a / b)
except Exception as e:
print("Error:", e)
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 24 Goal
โ Handle runtime errors
โ Write crash-free programs
โโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 25
๐ฅ User-Defined Exceptions
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
๐ PYTHON โ DAY 25 STUDY MATERIAL
โจ Topic: User-Defined Exceptions
โโโโโโโโโโโโโโโโโโโ
๐ What is a User-Defined Exception?
User-defined exceptions are custom errors created by programmers to handle specific situations.
โโโโโโโโโโโโโโโโโโโ
๐งฉ Why Use Custom Exceptions?
โ Clear error messages
โ Better control over program flow
โ Easy debugging
โโโโโโโโโโโโโโโโโโโ
๐น Creating a Custom Exception
Custom exceptions are created by inheriting from Exception class.
Example:
class AgeError(Exception):
pass
โโโโโโโโโโโโโโโโโโโ
๐น Raising a Custom Exception
Example:
def check_age(age):
if age < 18:
raise AgeError("Age must be 18 or above")
else:
print("Eligible")
โโโโโโโโโโโโโโโโโโโ
๐น Handling Custom Exception
Example:
try:
check_age(16)
except AgeError as e:
print(e)
โโโโโโโโโโโโโโโโโโโ
๐น Using raise Keyword
The raise keyword is used to trigger an exception manually.
Example:
raise ValueError("Invalid value")
โโโโโโโโโโโโโโโโโโโ
โ ๏ธ Important Notes
โข Custom exceptions should be meaningful
โข Always handle raised exceptions
โข Use inheritance properly
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 25
โ Create custom exception for login failure
โ Raise exception for invalid marks
โ Handle custom exception using try-except
Example Program:
class MarksError(Exception):
pass
marks = int(input("Enter marks: "))
if marks < 0 or marks > 100:
raise MarksError("Invalid marks")
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 25 Goal
โ Understand custom exception creation
โ Handle program-specific errors
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 26
๐ฅ Modules in Python
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
โจ Topic: User-Defined Exceptions
โโโโโโโโโโโโโโโโโโโ
๐ What is a User-Defined Exception?
User-defined exceptions are custom errors created by programmers to handle specific situations.
โโโโโโโโโโโโโโโโโโโ
๐งฉ Why Use Custom Exceptions?
โ Clear error messages
โ Better control over program flow
โ Easy debugging
โโโโโโโโโโโโโโโโโโโ
๐น Creating a Custom Exception
Custom exceptions are created by inheriting from Exception class.
Example:
class AgeError(Exception):
pass
โโโโโโโโโโโโโโโโโโโ
๐น Raising a Custom Exception
Example:
def check_age(age):
if age < 18:
raise AgeError("Age must be 18 or above")
else:
print("Eligible")
โโโโโโโโโโโโโโโโโโโ
๐น Handling Custom Exception
Example:
try:
check_age(16)
except AgeError as e:
print(e)
โโโโโโโโโโโโโโโโโโโ
๐น Using raise Keyword
The raise keyword is used to trigger an exception manually.
Example:
raise ValueError("Invalid value")
โโโโโโโโโโโโโโโโโโโ
โ ๏ธ Important Notes
โข Custom exceptions should be meaningful
โข Always handle raised exceptions
โข Use inheritance properly
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 25
โ Create custom exception for login failure
โ Raise exception for invalid marks
โ Handle custom exception using try-except
Example Program:
class MarksError(Exception):
pass
marks = int(input("Enter marks: "))
if marks < 0 or marks > 100:
raise MarksError("Invalid marks")
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 25 Goal
โ Understand custom exception creation
โ Handle program-specific errors
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 26
๐ฅ Modules in Python
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
๐ PYTHON โ DAY 26 STUDY MATERIAL
โจ Topic: Modules in Python
โโโโโโโโโโโโโโโโโโโ
๐ What is a Module?
A module is a file containing Python code (functions, variables, classes) that can be reused in another program.
It helps in code reusability and organization.
โโโโโโโโโโโโโโโโโโโ
๐ฆ Importing a Module
Syntax:
import module_name
Example:
import math
print(math.sqrt(25))
โโโโโโโโโโโโโโโโโโโ
๐น Import Specific Function
Syntax:
from module_name import function_name
Example:
from math import sqrt
print(sqrt(16))
โโโโโโโโโโโโโโโโโโโ
๐น Import with Alias
Example:
import math as m
print(m.pi)
โโโโโโโโโโโโโโโโโโโ
๐งฎ Common Built-in Modules
๐น math โ Mathematical operations
๐น random โ Random number generation
๐น datetime โ Date & time handling
๐น os โ Operating system functions
Example (random):
import random
print(random.randint(1, 10))
โโโโโโโโโโโโโโโโโโโ
๐ Creating User-Defined Module
Step 1: Create file mymodule.py
def greet():
print("Hello from module")
Step 2: Import in another file
import mymodule
mymodule.greet()
โโโโโโโโโโโโโโโโโโโ
โ ๏ธ Important Points
โข Module file must be in same folder
โข Avoid naming conflict with built-in modules
โข Use alias for shorter names
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 26
โ Use math module
โ Generate random number
โ Create your own module
โ Import specific function
Example Program:
from random import randint
print(randint(1, 100))
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 26 Goal
โ Understand module usage
โ Create reusable code files
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 27
๐ฅ OOP โ Class & Object
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
โจ Topic: Modules in Python
โโโโโโโโโโโโโโโโโโโ
๐ What is a Module?
A module is a file containing Python code (functions, variables, classes) that can be reused in another program.
It helps in code reusability and organization.
โโโโโโโโโโโโโโโโโโโ
๐ฆ Importing a Module
Syntax:
import module_name
Example:
import math
print(math.sqrt(25))
โโโโโโโโโโโโโโโโโโโ
๐น Import Specific Function
Syntax:
from module_name import function_name
Example:
from math import sqrt
print(sqrt(16))
โโโโโโโโโโโโโโโโโโโ
๐น Import with Alias
Example:
import math as m
print(m.pi)
โโโโโโโโโโโโโโโโโโโ
๐งฎ Common Built-in Modules
๐น math โ Mathematical operations
๐น random โ Random number generation
๐น datetime โ Date & time handling
๐น os โ Operating system functions
Example (random):
import random
print(random.randint(1, 10))
โโโโโโโโโโโโโโโโโโโ
๐ Creating User-Defined Module
Step 1: Create file mymodule.py
def greet():
print("Hello from module")
Step 2: Import in another file
import mymodule
mymodule.greet()
โโโโโโโโโโโโโโโโโโโ
โ ๏ธ Important Points
โข Module file must be in same folder
โข Avoid naming conflict with built-in modules
โข Use alias for shorter names
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 26
โ Use math module
โ Generate random number
โ Create your own module
โ Import specific function
Example Program:
from random import randint
print(randint(1, 100))
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 26 Goal
โ Understand module usage
โ Create reusable code files
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 27
๐ฅ OOP โ Class & Object
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
๐ PYTHON โ DAY 27 STUDY MATERIAL
โจ Topic: OOP โ Class & Object
โโโโโโโโโโโโโโโโโโโ
๐ What is OOP?
OOP (Object Oriented Programming) is a programming concept based on objects and classes.
It helps in:
โ Code reusability
โ Data security
โ Real-world modeling
โโโโโโโโโโโโโโโโโโโ
๐ท What is a Class?
A class is a blueprint for creating objects.
Syntax:
class ClassName:
pass
Example:
class Student:
pass
โโโโโโโโโโโโโโโโโโโ
๐ค What is an Object?
An object is an instance of a class.
Example:
s1 = Student()
Here, s1 is an object.
โโโโโโโโโโโโโโโโโโโ
๐น Class with Attributes
Example:
class Student:
name = "Soham"
age = 20
obj = Student()
print(obj.name)
โโโโโโโโโโโโโโโโโโโ
๐น init Constructor Method
Used to initialize object data.
Example:
class Student:
def init(self, name, age):
self.name = name
self.age = age
s1 = Student("Rahul", 22)
print(s1.name)
โโโโโโโโโโโโโโโโโโโ
๐น Instance Method
Example:
class Student:
def init(self, name):
self.name = name
def greet(self):
print("Hello", self.name)
s1 = Student("Amit")
s1.greet()
โโโโโโโโโโโโโโโโโโโ
๐ง Understanding self Keyword
โข self refers to the current object
โข It must be the first parameter in class methods
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 27
โ Create class Car with attributes
โ Create object of Car
โ Use constructor
โ Create method inside class
Example Program:
class Car:
def init(self, brand):
self.brand = brand
def show(self):
print("Brand:", self.brand)
c1 = Car("BMW")
c1.show()
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 27 Goal
โ Understand class & object
โ Use constructor and methods
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 28
๐ฅ OOP โ Encapsulation
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
โจ Topic: OOP โ Class & Object
โโโโโโโโโโโโโโโโโโโ
๐ What is OOP?
OOP (Object Oriented Programming) is a programming concept based on objects and classes.
It helps in:
โ Code reusability
โ Data security
โ Real-world modeling
โโโโโโโโโโโโโโโโโโโ
๐ท What is a Class?
A class is a blueprint for creating objects.
Syntax:
class ClassName:
pass
Example:
class Student:
pass
โโโโโโโโโโโโโโโโโโโ
๐ค What is an Object?
An object is an instance of a class.
Example:
s1 = Student()
Here, s1 is an object.
โโโโโโโโโโโโโโโโโโโ
๐น Class with Attributes
Example:
class Student:
name = "Soham"
age = 20
obj = Student()
print(obj.name)
โโโโโโโโโโโโโโโโโโโ
๐น init Constructor Method
Used to initialize object data.
Example:
class Student:
def init(self, name, age):
self.name = name
self.age = age
s1 = Student("Rahul", 22)
print(s1.name)
โโโโโโโโโโโโโโโโโโโ
๐น Instance Method
Example:
class Student:
def init(self, name):
self.name = name
def greet(self):
print("Hello", self.name)
s1 = Student("Amit")
s1.greet()
โโโโโโโโโโโโโโโโโโโ
๐ง Understanding self Keyword
โข self refers to the current object
โข It must be the first parameter in class methods
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 27
โ Create class Car with attributes
โ Create object of Car
โ Use constructor
โ Create method inside class
Example Program:
class Car:
def init(self, brand):
self.brand = brand
def show(self):
print("Brand:", self.brand)
c1 = Car("BMW")
c1.show()
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 27 Goal
โ Understand class & object
โ Use constructor and methods
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 28
๐ฅ OOP โ Encapsulation
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
๐ PYTHON โ DAY 28 STUDY MATERIAL
โจ Topic: OOP โ Encapsulation
โโโโโโโโโโโโโโโโโโโ
๐ What is Encapsulation?
Encapsulation means binding data (variables) and methods (functions) together in a single unit (class) and restricting direct access to some data.
It helps in:
โ Data protection
โ Better security
โ Controlled access
โโโโโโโโโโโโโโโโโโโ
๐ Access Modifiers in Python
Python does not have strict private/public like other languages, but it follows naming conventions:
๐น Public โ Accessible anywhere
๐น Protected โ Single underscore (_)
๐น Private โ Double underscore (__)
โโโโโโโโโโโโโโโโโโ
๐น Public Variable Example
class Student:
def init(self):
self.name = "Soham"
obj = Student()
print(obj.name)
โโโโโโโโโโโโโโโโโโโ
๐น Protected Variable Example
class Student:
def init(self):
self._age = 20
obj = Student()
print(obj._age)
(Note: Still accessible, but should not be accessed directly)
โโโโโโโโโโโโโโโโโโโ
๐ Private Variable Example
class Student:
def init(self):
self.__marks = 85
obj = Student()
print(obj.__marks) โ Error
To access private variable:
print(obj._Student__marks)
โโโโโโโโโโโโโโโโโโโ
๐น Getter and Setter Methods
Used to access and modify private data safely.
Example:
class Student:
def init(self):
self.__marks = 0
def set_marks(self, m):
self.__marks = m
def get_marks(self):
return self.__marks
s1 = Student()
s1.set_marks(90)
print(s1.get_marks())
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 28
โ Create class with private variable
โ Create getter & setter
โ Try accessing private variable directly
โ Understand name mangling
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 28 Goal
โ Understand data hiding
โ Use getter & setter properly
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 29
๐ฅ OOP โ Inheritance
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
โจ Topic: OOP โ Encapsulation
โโโโโโโโโโโโโโโโโโโ
๐ What is Encapsulation?
Encapsulation means binding data (variables) and methods (functions) together in a single unit (class) and restricting direct access to some data.
It helps in:
โ Data protection
โ Better security
โ Controlled access
โโโโโโโโโโโโโโโโโโโ
๐ Access Modifiers in Python
Python does not have strict private/public like other languages, but it follows naming conventions:
๐น Public โ Accessible anywhere
๐น Protected โ Single underscore (_)
๐น Private โ Double underscore (__)
โโโโโโโโโโโโโโโโโโ
๐น Public Variable Example
class Student:
def init(self):
self.name = "Soham"
obj = Student()
print(obj.name)
โโโโโโโโโโโโโโโโโโโ
๐น Protected Variable Example
class Student:
def init(self):
self._age = 20
obj = Student()
print(obj._age)
(Note: Still accessible, but should not be accessed directly)
โโโโโโโโโโโโโโโโโโโ
๐ Private Variable Example
class Student:
def init(self):
self.__marks = 85
obj = Student()
print(obj.__marks) โ Error
To access private variable:
print(obj._Student__marks)
โโโโโโโโโโโโโโโโโโโ
๐น Getter and Setter Methods
Used to access and modify private data safely.
Example:
class Student:
def init(self):
self.__marks = 0
def set_marks(self, m):
self.__marks = m
def get_marks(self):
return self.__marks
s1 = Student()
s1.set_marks(90)
print(s1.get_marks())
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 28
โ Create class with private variable
โ Create getter & setter
โ Try accessing private variable directly
โ Understand name mangling
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 28 Goal
โ Understand data hiding
โ Use getter & setter properly
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 29
๐ฅ OOP โ Inheritance
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
๐ PYTHON โ DAY 29 STUDY MATERIAL
โจ Topic: OOP โ Inheritance
โโโโโโโโโโโโโโโโโโโ
๐ What is Inheritance?
Inheritance allows one class to reuse the properties and methods of another class.
โ Code Reusability
โ Reduces redundancy
โ Improves maintainability
โโโโโโโโโโโโโโโโโโโ
๐จโ๐ฆ Parent & Child Class
๐น Parent Class โ Base Class
๐น Child Class โ Derived Class
Syntax:
class Parent:
pass
class Child(Parent):
pass
โโโโโโโโโโโโโโโโโโโ
๐น Basic Inheritance Example
class Person:
def greet(self):
print("Hello from Parent")
class Student(Person):
pass
s1 = Student()
s1.greet() # Inherited method
โโโโโโโโโโโโโโโโโโโ
๐น Inheritance with Constructor
class Person:
def init(self, name):
self.name = name
class Student(Person):
def display(self):
print("Name:", self.name)
s1 = Student("Rahul")
s1.display()
โโโโโโโโโโโโโโโโโโโ
๐น Using super() Function
Used to call parent class constructor.
class Person:
def init(self, name):
self.name = name
class Student(Person):
def init(self, name, age):
super().init(name)
self.age = age
def display(self):
print(self.name, self.age)
s1 = Student("Amit", 21)
s1.display()
โโโโโโโโโโโโโโโโโโโ
๐น Types of Inheritance in Python
1๏ธโฃ Single Inheritance
2๏ธโฃ Multiple Inheritance
3๏ธโฃ Multilevel Inheritance
4๏ธโฃ Hierarchical Inheritance
5๏ธโฃ Hybrid Inheritance
โโโโโโโโโโโโโโโโโโโ
๐ง Multilevel Inheritance Example
class A:
def methodA(self):
print("Class A")
class B(A):
def methodB(self):
print("Class B")
class C(B):
def methodC(self):
print("Class C")
obj = C()
obj.methodA()
obj.methodB()
obj.methodC()
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 29
โ Create Parent class Vehicle
โ Create Child class Car
โ Use super()
โ Try multilevel inheritance
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 29 Goal
โ Understand Parent & Child relationship
โ Use super() correctly
โ Practice different inheritance types
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 30
๐ฅ OOP โ Polymorphism
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
โจ Topic: OOP โ Inheritance
โโโโโโโโโโโโโโโโโโโ
๐ What is Inheritance?
Inheritance allows one class to reuse the properties and methods of another class.
โ Code Reusability
โ Reduces redundancy
โ Improves maintainability
โโโโโโโโโโโโโโโโโโโ
๐จโ๐ฆ Parent & Child Class
๐น Parent Class โ Base Class
๐น Child Class โ Derived Class
Syntax:
class Parent:
pass
class Child(Parent):
pass
โโโโโโโโโโโโโโโโโโโ
๐น Basic Inheritance Example
class Person:
def greet(self):
print("Hello from Parent")
class Student(Person):
pass
s1 = Student()
s1.greet() # Inherited method
โโโโโโโโโโโโโโโโโโโ
๐น Inheritance with Constructor
class Person:
def init(self, name):
self.name = name
class Student(Person):
def display(self):
print("Name:", self.name)
s1 = Student("Rahul")
s1.display()
โโโโโโโโโโโโโโโโโโโ
๐น Using super() Function
Used to call parent class constructor.
class Person:
def init(self, name):
self.name = name
class Student(Person):
def init(self, name, age):
super().init(name)
self.age = age
def display(self):
print(self.name, self.age)
s1 = Student("Amit", 21)
s1.display()
โโโโโโโโโโโโโโโโโโโ
๐น Types of Inheritance in Python
1๏ธโฃ Single Inheritance
2๏ธโฃ Multiple Inheritance
3๏ธโฃ Multilevel Inheritance
4๏ธโฃ Hierarchical Inheritance
5๏ธโฃ Hybrid Inheritance
โโโโโโโโโโโโโโโโโโโ
๐ง Multilevel Inheritance Example
class A:
def methodA(self):
print("Class A")
class B(A):
def methodB(self):
print("Class B")
class C(B):
def methodC(self):
print("Class C")
obj = C()
obj.methodA()
obj.methodB()
obj.methodC()
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 29
โ Create Parent class Vehicle
โ Create Child class Car
โ Use super()
โ Try multilevel inheritance
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 29 Goal
โ Understand Parent & Child relationship
โ Use super() correctly
โ Practice different inheritance types
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 30
๐ฅ OOP โ Polymorphism
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
๐ PYTHON โ DAY 30 STUDY MATERIAL
โจ Topic: OOP โ Polymorphism
โโโโโโโโโโโโโโโโโโโ
๐ What is Polymorphism?
Polymorphism means โmany formsโ.
In Python, it allows the same function name to behave differently depending on the object.
โ Increases flexibility
โ Improves readability
โ Makes code scalable
โโโโโโโโโโโโโโโโโโโ
๐น Method Overriding (Runtime Polymorphism)
When a child class provides a different implementation of a method from the parent class.
Example:
class Animal:
def sound(self):
print("Animal makes sound")
class Dog(Animal):
def sound(self):
print("Dog barks")
obj = Dog()
obj.sound()
Output:
Dog barks
โโโโโโโโโโโโโโโโโโโ
๐น Polymorphism with Multiple Classes
class Cat:
def sound(self):
print("Meow")
class Dog:
def sound(self):
print("Bark")
def make_sound(animal):
animal.sound()
make_sound(Cat())
make_sound(Dog())
Same function โ Different behavior
โโโโโโโโโโโโโโโโโโโ
๐น Operator Overloading
Python allows operators to behave differently for different data types.
Example:
print(5 + 3) # 8
print("Hi " + "All") # Hi All
โ+โ works for numbers and strings differently.
โโโโโโโโโโโโโโโโโโโ
๐น Method Overloading in Python?
Python does NOT support traditional method overloading like Java.
But we can simulate it using default arguments:
class Calculator:
def add(self, a, b=0, c=0):
return a + b + c
obj = Calculator()
print(obj.add(5))
print(obj.add(5, 3))
print(obj.add(5, 3, 2))
โโโโโโโโโโโโโโโโโโโ
๐ง Real Life Example
Think about a โPaymentโ system:
โ Credit Card Payment
โ UPI Payment
โ Net Banking
All use a method like pay(), but the implementation is different.
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 30
โ Create class Shape with method area()
โ Override area() in Circle & Rectangle
โ Create common function to call area()
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 30 Goal
โ Understand Method Overriding
โ Understand Dynamic Polymorphism
โ Practice real-life examples
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 31
๐ฅ OOP โ Abstraction
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
โจ Topic: OOP โ Polymorphism
โโโโโโโโโโโโโโโโโโโ
๐ What is Polymorphism?
Polymorphism means โmany formsโ.
In Python, it allows the same function name to behave differently depending on the object.
โ Increases flexibility
โ Improves readability
โ Makes code scalable
โโโโโโโโโโโโโโโโโโโ
๐น Method Overriding (Runtime Polymorphism)
When a child class provides a different implementation of a method from the parent class.
Example:
class Animal:
def sound(self):
print("Animal makes sound")
class Dog(Animal):
def sound(self):
print("Dog barks")
obj = Dog()
obj.sound()
Output:
Dog barks
โโโโโโโโโโโโโโโโโโโ
๐น Polymorphism with Multiple Classes
class Cat:
def sound(self):
print("Meow")
class Dog:
def sound(self):
print("Bark")
def make_sound(animal):
animal.sound()
make_sound(Cat())
make_sound(Dog())
Same function โ Different behavior
โโโโโโโโโโโโโโโโโโโ
๐น Operator Overloading
Python allows operators to behave differently for different data types.
Example:
print(5 + 3) # 8
print("Hi " + "All") # Hi All
โ+โ works for numbers and strings differently.
โโโโโโโโโโโโโโโโโโโ
๐น Method Overloading in Python?
Python does NOT support traditional method overloading like Java.
But we can simulate it using default arguments:
class Calculator:
def add(self, a, b=0, c=0):
return a + b + c
obj = Calculator()
print(obj.add(5))
print(obj.add(5, 3))
print(obj.add(5, 3, 2))
โโโโโโโโโโโโโโโโโโโ
๐ง Real Life Example
Think about a โPaymentโ system:
โ Credit Card Payment
โ UPI Payment
โ Net Banking
All use a method like pay(), but the implementation is different.
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 30
โ Create class Shape with method area()
โ Override area() in Circle & Rectangle
โ Create common function to call area()
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 30 Goal
โ Understand Method Overriding
โ Understand Dynamic Polymorphism
โ Practice real-life examples
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 31
๐ฅ OOP โ Abstraction
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
๐ PYTHON โ DAY 31 STUDY MATERIAL
โจ Topic: OOP โ Abstraction
โโโโโโโโโโโโโโโโโโโ
๐ What is Abstraction?
Abstraction means hiding implementation details and showing only essential features.
Example in real life ๐
You drive a car without knowing how the engine works internally.
โ Hides complexity
โ Improves security
โ Focus on what, not how
โโโโโโโโโโโโโโโโโโโ
๐น How to Achieve Abstraction in Python?
Using the abc (Abstract Base Class) module
We import:
from abc import ABC, abstractmethod
โโโโโโโโโโโโโโโโโโโ
๐น Creating an Abstract Class
Example:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
This class cannot be instantiated directly.
โโโโโโโโโโโโโโโโโโโ
๐น Implementing Abstract Method in Child Class
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
print("Dog barks")
obj = Dog()
obj.sound()
If we donโt implement sound(), it gives error โ
โโโโโโโโโโโโโโโโโโโ
๐น Why Use Abstraction?
โ To enforce method implementation
โ To create standard structure
โ To design scalable applications
โโโโโโโโโโโโโโโโโโโ
๐ง Real World Example
Payment System:
class Payment(ABC):
@abstractmethod
def pay(self):
pass
class UPI(Payment):
def pay(self):
print("Paid using UPI")
class Card(Payment):
def pay(self):
print("Paid using Card")
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 31
โ Create abstract class Shape
โ Create area() abstract method
โ Implement in Circle & Rectangle
โ Try creating object of abstract class (see error)
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 31 Goal
โ Understand abstraction
โ Use abc module
โ Implement abstract methods
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 32
๐ฅ OOP โ Special (Magic/Dunder) Methods
โจ Stay Connected | Keep Coding
๐ TechByWebCoder
โจ Topic: OOP โ Abstraction
โโโโโโโโโโโโโโโโโโโ
๐ What is Abstraction?
Abstraction means hiding implementation details and showing only essential features.
Example in real life ๐
You drive a car without knowing how the engine works internally.
โ Hides complexity
โ Improves security
โ Focus on what, not how
โโโโโโโโโโโโโโโโโโโ
๐น How to Achieve Abstraction in Python?
Using the abc (Abstract Base Class) module
We import:
from abc import ABC, abstractmethod
โโโโโโโโโโโโโโโโโโโ
๐น Creating an Abstract Class
Example:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
This class cannot be instantiated directly.
โโโโโโโโโโโโโโโโโโโ
๐น Implementing Abstract Method in Child Class
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
print("Dog barks")
obj = Dog()
obj.sound()
If we donโt implement sound(), it gives error โ
โโโโโโโโโโโโโโโโโโโ
๐น Why Use Abstraction?
โ To enforce method implementation
โ To create standard structure
โ To design scalable applications
โโโโโโโโโโโโโโโโโโโ
๐ง Real World Example
Payment System:
class Payment(ABC):
@abstractmethod
def pay(self):
pass
class UPI(Payment):
def pay(self):
print("Paid using UPI")
class Card(Payment):
def pay(self):
print("Paid using Card")
โโโโโโโโโโโโโโโโโโโ
๐ Practice Tasks โ Day 31
โ Create abstract class Shape
โ Create area() abstract method
โ Implement in Circle & Rectangle
โ Try creating object of abstract class (see error)
โโโโโโโโโโโโโโโโโโโ
๐ฏ Day 31 Goal
โ Understand abstraction
โ Use abc module
โ Implement abstract methods
โโโโโโโโโโโโโโโโโโโ
๐ Next Topic โ Day 32
๐ฅ OOP โ Special (Magic/Dunder) Methods
โจ Stay Connected | Keep Coding
๐ TechByWebCoder