Machine Learning Part 01
Machine Learning Part 01
1. Basics of Python
2. Operators in Python
3. Loops in Python
4. Strings in Python (part-1)
5. Strings in Python (part-2)
6. Problems on Strings
7. Basics-Operators-If-else-loops-and-Strings-In-
PYTHON
8. List in Python (Part-1)
9. List in Python (Part-2)
10. Tuples in Python
11. Sets in Python
12. Dictionary in Python
13. OOP in python (Part 01)
14. OOP in python (Part 02)
15. Problems on OOP
16. Encapsulation in Python
17. Aggregation OOP
18. Inheritance in OOP
19. Polymorphism and Abstraction
Python Output
In [1]: # Python is case sensitive
print('Hello World')
Hello World
In [50]: print(hey) # it throws error beacuse only string is always in " "
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_9556\1311815035.py in <module>
----> 1 print(hey) # it throws error beacuse only string always in " "
In [3]: print(7)
In [4]: print(True)
True
In [5]: # how print function strng in python -- it print all the values which we want to pr
print('Hello',3,4,5,True)
Hello 3 4 5 True
In [6]: # sep
print('Hello',3,4,5,True,sep='/') # sep is separator where in print function space
Hello/3/4/5/True
In [7]: print('hello')
print('world')
hello
world
In [8]: # end
print('you',end="=")
print ('me')
you=me
2. Float (Decimal)
In [10]: print(8.44)
localhost:8888/nbconvert/html/Downloads/Pythoon 100 Days/100_Days_OF_Python/Day 1 - Basics OF Python.ipynb?download=false 1/7
9/20/23, 10:21 AM Day 1 - Basics OF Python
8.44
3. Boolean
In [11]: print(True)
print(False)
True
False
4. String (Text)
In [12]: print('Hello gem')
Hello gem
5. Complex
In [13]: print(5+6j)
(5+6j)
6. List
In Python, a list is a data type used to store a collection of values. It is one of the built-in
data types and is classified as a sequence type. Lists are ordered, mutable (which means you
can change their contents), and can contain elements of different data types, including
integers, floats, strings, or even other lists.
You can create a list in Python by enclosing a comma-separated sequence of values within
square brackets [ ]. For example:
In [ ]: print([1,2,3,4])
7. Tuple
In Python, a tuple is another data type used to store a collection of values, similar to a list.
However, there are some key differences between tuples and lists:
Immutable: The most significant difference is that tuples are immutable, meaning once
you create a tuple, you cannot change its contents (add, remove, or modify elements).
Lists, on the other hand, are mutable, and you can modify them after creation.
Tuples are often used when you have a collection of values that should not be changed
during the course of your program. For example, you might use tuples to represent
coordinates (x, y), dates (year, month, day), or other data where the individual components
should remain constant.
In [14]: print((1,2,3,4))
(1, 2, 3, 4)
8. sets
In Python, a set is a built-in data type used to store an unordered collection of unique
elements. Sets are defined by enclosing a comma-separated sequence of values within curly
braces {} or by using the built-in set() constructor. Sets automatically eliminate duplicate
values, ensuring that each element is unique within the set.
In [15]: print({1,2,3,4,5})
{1, 2, 3, 4, 5}
9. Dictionary
In Python, a dictionary is a built-in data type used to store a collection of key-value pairs.
Each key in a dictionary maps to a specific value, creating a relationship between them.
Dictionaries are also known as associative arrays or hash maps in other programming
languages.
In [16]: print({'name':'Nitish','gender':'Male','weight':70})
list
Out[18]:
In [19]: type({'age':20})
dict
Out[19]:
1. Variable Names: Variable names (also known as identifiers) must adhere to the
following rules:
They can contain letters (a-z, A-Z), digits (0-9), and underscores (_).
They cannot start with a digit.
Variable names are case-sensitive, so myVar and myvar are treated as different
variables.
Python has reserved keywords (e.g., if, for, while, print) that cannot be used as variable
names.
1. Data Types: Python is dynamically typed, which means you don't need to declare the
data type of a variable explicitly. Python will determine the data type automatically
based on the assigned value.
1. Reassignment: You can change the value of a variable by assigning it a new value.
In [23]: x = 5
x = x + 1 # Updating the value of 'x' to 6
In [24]: print(x)
Multiple Assignment: Python allows you to assign multiple variables in a single line.
In [28]: print(a)
In [29]: a = 1
b = 2
c = 3
print(a,b,c)
1 2 3
In [30]: a=b=c= 5
print(a,b,c)
5 5 5
1. Single-line Comments: Single-line comments start with the hash symbol ( # ) and
continue until the end of the line. They are used to add comments on a single line.
1. Multi-line or Block Comments: Python does not have a specific syntax for multi-line
comments like some other languages (e.g., C, Java). However, you can create multi-line
comments by using triple-quotes ( ''' or """ ) as a string delimiter. These strings are
not assigned to any variable and are ignored by the interpreter. This is a common
practice for writing docstrings (documentation within functions and modules).
In [34]: '''
This is a multi-line comment.
It can span multiple lines.
'''
def my_function():
"""
This is a docstring.
It provides documentation for the function.
"""
pass
While these triple-quoted strings are not technically comments, they are often used as a
way to document code effectively.
Comments are crucial for making your code more understandable, both for yourself and for
others who may read your code. They help explain the purpose of variables, functions, and
complex algorithms, making it easier to maintain and debug code. Good commenting
practices can significantly improve code readability and maintainability.
Enter EmailSagar@95
'Sagar@95'
Out[35]:
print(result)
print(type(fnum))
5. Type Conversion
How to covert One Datatypeinto another In python?
int(): Converts a value to an integer data type. This is useful when you want to convert a
string or a floating-point number to an integer.
123
Out[44]:
In [45]: int_value = 42
float_value = float(int_value) # Converts the integer 42 to a float
float_value
42.0
Out[45]:
In [37]: a = 23
b = "24"
print(a+b)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_9556\3112067906.py in <module>
2 b = "24"
3
----> 4 print(a+b)
It Gives error beacause We do not add float into integer datatyupe so we have to convert
above opeartion
In [38]: a = 23
b = "24"
print(float(a)+float(b))
47.0
6. Literals
localhost:8888/nbconvert/html/Downloads/Pythoon 100 Days/100_Days_OF_Python/Day 1 - Basics OF Python.ipynb?download=false 6/7
9/20/23, 10:21 AM Day 1 - Basics OF Python
In Python, literals are used to represent fixed values in your code. These values are not
variables or expressions but rather constants that have a specific value and data type
associated with them. Python supports various types of literals,
#Float Literal
float_1 = 10.5
float_2 = 1.5e2 # 1.5 * 10^2
float_3 = 1.5e-3 # 1.5 * 10^-3
#Complex Literal
x = 3.14j
print(a, b, c, d)
print(float_1, float_2,float_3)
print(x, x.imag, x.real)
In [48]: # binary
x = 3.14j
print(x.imag)
3.14
print(string)
print(strings)
print(char)
print(multiline_str)
print(unicode)
print(raw_str)
This is Python
This is Python
C
This is a multiline string with more than one line code.
😀😆🤣
raw \n string
Operators In Python
1.Arithmetic Operators:
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Floor Division (//)
Modulus (%)
Exponentiation (**)
print(5//2) # Floor Division -> It trasform into integer number= 2.5 convert into 2
11
-1
30
2.5
2
1
25
In [5]: print(4==4)
print(4!=4)
print(4<5)
print(4>5)
print(4<=4)
print(4>=4)
True
False
True
False
True
True
2. Logical Operators:
Logical AND (and)
Logical OR (or)
Logical NOT (not)
In [7]: p = True
q = False
False
True
False
3. Assignment Operators:
Assignment (=)
Add and Assign (+=)
Subtract and Assign (-=)
Multiply and Assign (*=)
Divide and Assign (/=)
Floor Divide and Assign (//=)
Modulus and Assign (%=)
Exponentiate and Assign (**=)
In [12]: x = 10
x += 5
print(x) # Equivalent to x = x + 5
15
In [16]: x = 10
x -= 3 # Equivalent to x = x - 3
x *= 2 # Equivalent to x = x * 2
x /= 4 # Equivalent to x = x / 4
x //= 2 # Equivalent to x = x // 2
x %= 3 # Equivalent to x = x % 3
x **= 2 # Equivalent to x = x ** 2
4.Bitwise Operators:
Bitwise AND (&)
Bitwise OR (|)
Bitwise XOR (^)
Bitwise NOT (~)
Left Shift (<<)
Right Shift (>>)
1
7
6
-6
10
2
These are the basic operators in Python. You can use them to perform various operations on
variables and values in your Python programs.
Loops In Python
In Python, loops are used to execute a block of code repeatedly
There are two main types of loops in Python: ### 1. 'For' loops ### 2. 'While' loops ###
3. Loops Controls Statement
1. For loops
A 'for loop' is used to iterate over a sequence (such as a list, tuple, string, or range) and
execute a block of code for each item in the sequence.
for i in range(1,11): # in for loop we have to sepcify the range or also mention
print(i)
1
2
3
4
5 Machine Learning Part 02:
6
7
https://t.me/AIMLDeepThaught/689
8
9
10
for i in (1,2,3,4,5,6,7,8):
print(i)
# for loop is very very flexible and powerful in python it used with all datatypes
1
2
3
4
5
6
7
8
1
3
5
7
9
11
13
15
17
19
The 2 inside the range() function is called the "step" or "stride." It determines the
increment between each consecutive value in the range. In this case, the loop will
iterate over the numbers from 1 to 20, with a step of 2.
So, the loop will print the following numbers: 1, 3, 5, 7, 9, 11, 13, 15, 17, and 19. The
loop starts at 1, increments by 2 in each iteration, and stops before reaching or
exceeding 21.
for i in range(10,0,-1):
print(i)
10
9
8
7
6
5
4
3
2
1
curr_pop /= 1.1
10 10000
9 9090.90909090909
8 8264.462809917353
7 7513.148009015775
6 6830.134553650703
5 6209.213230591548
4 5644.739300537771
3 5131.5811823070635
2 4665.07380209733
1 4240.976183724845
2. While Loop
A while loop is used to repeatedly execute a block of code as long as a certain
condition is true.
1
2
3
4
5
i = 1
while i<11:
print(num * i)
i+=1
'continue': Skips the current iteration of the loop and proceeds to the next iteration.
'else' clause: Can be used with a for or while loop to specify a block of code that will be
executed after the loop has finished normally (i.e., without hitting a break statement).
while x < 3:
print(x)
x += 1
else:
print('limit Crossed')
1
2
limit Crossed
print("Loop ended")
1
2
3
4
5
Loop ended
In this example, the loop will print numbers 1 through 5 and then exit the loop when num
becomes 6 due to the break statement. The "Loop ended" message will be printed after the
loop finishes.
numbers = [1, 2, 3, 4, 5]
print("Loop ended")
1
2
4
5
Loop ended
In this example, when num equals 3, the continue statement is encountered, which skips the
printing of 3 and moves on to the next iteration. As a result, the loop will print numbers 1, 2,
4, and 5. The "Loop ended" message will be printed after the loop finishes.
1
2
4
Loop finished normally
Immutable: Strings in Python are immutable, meaning once you create a string, you
cannot change its content. You can create new strings based on the original string, but
the original string remains unchanged.
1. Creating Strings
In [ ]: # create string with the help of single quotes
s = 'Hello World'
print(s)
Hello World
Hello World
-> In Python, you can create strings using both single quotes (') and double quotes ("), and
they are functionally equivalent. The choice between using single or double quotes mainly
depends on your personal preference or specific coding style guidelines.
If your string contains a quotation mark character (either a single quote or double quote),
you can use the other type of quote to define the string without escaping the inner quotes.
This can make your code more readable:
He said, "Hello!"
He said, 'Hello!'
In [ ]: # multiline strings
s = '''hello'''
s = """hello"""
s = str('hello')
print(s)
hello
Indexing
Indexing in Python refers to the process of accessing individual elements or characters
within a sequence, such as a string. Strings in Python are sequences of characters, and you
can access specific characters in a string using indexing. Indexing is done using square
brackets [ ], and Python uses a zero-based indexing system, meaning the first element has
an index of 0, the second element has an index of 1, and so on.
In [ ]: s = "Hello World"
H
e
In [ ]: # Accessing individual characters using negative indexing (counting from the end)
print(s[-1]) # Accesses the last character, 'd'
print(s[-2]) # Accesses the second-to-last character, 'l'
d
l
Slicing
In Python, slicing is a technique used to extract a portion of a string, list, or any other
sequence-like data structure. When it comes to strings, slicing allows you to create a new
string by specifying a range of indices to extract a substring from the original string.
In [ ]: # string[start:end]
In [ ]: s = 'hello world'
print(s[1:5]) # from 1 index that is e to 4 index=o
print(s[:6]) # from 0 to 5
print(s[1:]) # from 1 to all
print(s[:]) # all string
print(s[-5:-1]) # with negative slicing
ello
hello
ello world
hello world
worl
wol
dlrow olleh
In [ ]: s = 'hello world'
print(s[-1:-6:-1])
dlrow
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_4564\2237226474.py in <module>
1 s = 'hello world'
----> 2 s[0] = 'H'
3
4 # Python strings are immutable
Immutable: Strings in Python are immutable, meaning once you create a string, you cannot
change its content. You can create new strings based on the original string, but the original
string remains unchanged.
operations on strings
In Python, strings are sequences of characters and are very versatile. You can perform a wide
range of operations on strings, including but not limited to:
1. Concatenation
You can concatenate (combine) two or more strings using the '+' operator:
# if we want space
print(a + " " + b)
Helloworld
Hello world
delhidelhidelhidelhidelhidelhidelhidelhidelhidelhidelhidelhidelhidelhi
In [ ]: print("*"*50)
**************************************************
In [ ]: s = "Hello world"
'l'
Out[ ]:
In [ ]: s[4:9]
'o wor'
Out[ ]:
3. String Methods
Python provides many built-in string methods for common operations like converting to
uppercase, lowercase, finding substrings, replacing, and more
Upper
file:///C:/Users/disha/Downloads/Day6 - Strings in Python part 2.html 1/3
9/25/23, 10:26 AM Day6 - Strings in Python part 2
HELLO, WORLD!
Lower
hello, world!
find
replace
Hi, World!
4. String Formatting
You can format strings using f-strings or the str.format() method
In [ ]: name = 'nitish'
gender = 'male'
4. String Length
You can find the length of a string using the len() function
13
5. Strip
In [ ]: 'hey '.strip() # it drop the Unwanted space prenet
'hey'
Out[ ]:
In [ ]:
Problems on Strings
1 . Find the length of a given string without using the len() function
counter = 0
for i in s:
counter += 1
print(s)
print('lenght of string is',counter)
Dishant
lenght of string is 7
pos = s.index('@')
print(s)
print(s[0:pos])
xyz123@gmail.com
xyz123
Eg 'hello how are you' is the string, the frequency of h in this string is 2.
counter = 0
for i in s:
if i == term:
counter += 1
print('frequency',counter)
frequency 1
result = ''
for i in s:
if i != term:
result = result + i
print(result)
5. Write a program that can check whether a given string is palindrome or not.
abba
malayalam
if flag:
print('Palindrome')
abba
Palindrome
if i != ' ':
temp = temp + i
else:
L.append(temp)
temp = ''
L.append(temp)
print(L)
7. Write a python program to convert a string to title case without using the title()
L = []
for i in s.split():
L.append(i[0].upper() + i[1:].lower())
print(" ".join(L))
digits = '0123456789'
result = ''
while number != 0:
result = digits[number % 10] + result
number = number//10
print(result)
print(type(result))
143243
143243
<class 'str'>
In [ ]:
1. int: This data type is used to represent integers, both positive and negative whole
numbers. For example, x = 5 or y = -10 .
2. float: Floats are used to represent floating-point numbers, which include decimal
points. For example, pi = 3.14159 or value = 2.5 .
3. str: Strings are used to represent sequences of characters, such as text. They can be
enclosed in single quotes (' '), double quotes (" "), or triple quotes for multi-line strings.
For example, name = "Alice" or sentence = 'Hello, World!' .
4. bool: Booleans represent either True or False . They are used for logical operations
and comparisons. For example, is_true = True or is_false = False .
5. list: Lists are ordered collections of items. They can contain elements of different data
types, and the elements can be changed (mutable). For example, my_list = [1, 2,
'three', True] .
6. tuple: Tuples are similar to lists but are immutable, meaning their elements cannot be
changed after creation. They are often used to represent fixed collections of items. For
example, my_tuple = (1, 2, 'three') .
7. dict (dictionary): Dictionaries are collections of key-value pairs, where each key is
unique. They are used to store and retrieve data using keys. For example, person =
{'name': 'John', 'age': 30} .
8. set: Sets are unordered collections of unique elements. They are used for tasks like
removing duplicates or checking for membership. For example, my_set = {1, 2,
3} .
9. NoneType: The None type represents the absence of a value or a null value. It is often
used to indicate that a variable or result has no meaningful value assigned to it.
10. complex: Complex numbers represent numbers with both real and imaginary parts.
They are written as a + bj , where a is the real part, and b is the imaginary part.
For example, z = 3 + 4j .
11. bytes and bytearray: These data types are used to represent sequences of bytes, often
used for binary data or working with file I/O.
12. range: The range type is used to generate a sequence of numbers, commonly used in
for loops and iterations.
13. datetime: The datetime data type is used to represent dates and times and provides
functionality for working with dates and times.
Identity operators: The “is” and “is not” keywords are called identity operators that
compare objects based on their identity. Equality operator: The “==” and “!=” are called
equality operators that compare the objects based on their values.
A module is a Python file that’s intended to be imported into scripts or other modules.
It often defines members like classes, functions, and variables intended to be used in
other files that import it.
A library is an umbrella term that loosely means “a bundle of code.” These can have
tens or even hundreds of individual modules that can provide a wide range of
functionality. Matplotlib is a plotting library. The Python Standard Library contains
hundreds of modules for performing common tasks, like sending emails or reading
JSON data. What’s special about the Standard Library is that it comes bundled with your
installation of Python, so you can use its modules without having to download them
from anywhere.
A 'for' loop is used for iterating over a sequence (such as a list, tuple, or string) or other
iterable objects. It repeatedly executes a block of code for each item in the sequence.
Alt text
Characterstics of a List:
Ordered
Changeble/Mutable
Hetrogeneous
Can have duplicates
are dynamic
can be nested
items can be accessed
can contain any kind of objects in python
Creating a List
In [ ]: # Empty
print([])
# 1D -> Homo
print([1,2,3,4,5])
# 2D
print([1,2,3,[4,5]])
# 3D
print([[[1,2],[3,4]]])
# Heterogenous
print([1,True,5.6,5+6j,'Hello'])
[]
[1, 2, 3, 4, 5]
[1, 2, 3, [4, 5]]
[[[1, 2], [3, 4]]]
[1, True, 5.6, (5+6j), 'Hello']
['h', 'e', 'l', 'l', 'o']
Indexing
Slicing
In [ ]: # indexing
L = [[[1,2],[3,4]],[[5,6],[7,8]]]
L1 = [1,2,3,4]
# Positive Indexing
print(L1[1:4])
print(L[0][0][1]) # for 2
#How to extract 6
print(L[1][0][1])
[2, 3, 4]
[]
2
6
In [ ]: # Negative indexing
L = [[[1,2],[3,4]],[[5,6],[7,8]]]
L1 = [1,2,3,4]
print(L[-1])
In [ ]: # Slicing
L = [1,2,3,4,5,6]
print(L[::-1])
[6, 5, 4, 3, 2, 1]
[1, 2, 3, 4, 5, True]
In [ ]: # Extend -> The extend method is used to append elements from an iterable (e.g., an
L = [1,2,3,4,5]
L.extend([2])
L
[1, 2, 3, 4, 5, 2]
Out[ ]:
In [ ]: # insert -> The insert method allows you to add an item at a specific position in t
l = [1,2,3,4]
l.insert(1,100)
print(l)
[1, 2, 3, 4, 5, 300]
[1, 200, 300, 400, 5, 300]
#indexing
del l[2]
print(l)
# slicing
del l[2:4]
print(l)
[1, 2, 4, 5]
[1, 2]
In [ ]: # remove -> The remove method is used to remove the first occurrence of a specific
l = [1,2,3]
l.remove(2)
print(l)
[1, 3]
In [ ]: # pop -> The pop method is used to remove and return an item from the list based on
# If you don't provide an index, it will remove and return the last item by default
L = [1,2,3,4,5]
L.pop()
print(L)
[1, 2, 3, 4]
In [ ]: # clear -> The clear method is used to remove all items from the list, effectively
L = [1,2,3,4,5]
L.clear()
print(L)
[]
In [ ]:
In [ ]:
In [ ]:
Operations on Lists:
There are three types of Opeartion in List:
1. Arithmatic
2. Membership
3. Loop
L1 = [1,2,3,4,5]
L2 = [9,8,7,6,5]
# concatenation/Merge
print(L1 + L2)
print(L1*3)
print(L2*4)
[1, 2, 3, 4, 5, 9, 8, 7, 6, 5]
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
[9, 8, 7, 6, 5, 9, 8, 7, 6, 5, 9, 8, 7, 6, 5, 9, 8, 7, 6, 5]
In [ ]: # membership
L1 = [1,2,3,4,5]
L2 = [1,2,3,4,[5,6]]
False
True
In [ ]: # loops
L1 = [1,2,3,4,5]
L2 = [1,2,3,4,[5,6]]
L3 = [[[1,2],[3,4]],[[5,6],[7,8]]]
for i in L2:
print(i)
1
2
3
4
[5, 6]
List Functions
In [ ]: # len/min/max/sorted
L = [2,1,5,7,0]
print(len(L))
5
7
0
[0, 1, 2, 5, 7]
In [ ]: # count
l = [1,2,3,456,67867]
l.count(456)
1
Out[ ]:
In [ ]: # index
l = [3,5,7,9,3,23]
l.index(5)
1
Out[ ]:
In [ ]: # reverse
l = [1,2,3,4,6,78]
l.reverse()
print(l)
[78, 6, 4, 3, 2, 1]
In [ ]: # sort vs sorted
L = [2,1,5,7,0]
print(L)
print(sorted(L))
print(L)
L.sort()
print(L)
[2, 1, 5, 7, 0]
[0, 1, 2, 5, 7]
[2, 1, 5, 7, 0]
[0, 1, 2, 5, 7]
If you want to sort a list in-place, you should use the sort method. If you want to create a
new sorted list without modifying the original list, you should use the sorted function
List Comprehension
List Comprehension provides a concise way of creating lists.
print(L)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [ ]: # By List Comprehension
L = [i for i in range(1,11)]
print(L)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
L = [v*i for i in c]
print(L)
In [ ]: # Add sqaures
L = [2,3,4,5,6]
[i**2 for i in L]
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
Out[ ]:
In [ ]: a = [1,2,3]
b = a.copy()
print(a)
print(b)
a.append(4)
print(a)
print(b)
In [ ]:
Tuples In Python
A tuple in Python is an immutable, ordered collection of elements. It is similar to a list in that
it can store a variety of data types, including numbers, strings, and other objects, but unlike
lists, tuples cannot be modified once they are created.
This immutability means that you can't add, remove, or change elements within a tuple after
it's been defined.
Characterstics
Ordered
Unchangeble
Allows duplicate
Creating Tuples
In [ ]: # How to create empty tuple
t1 =()
print(t1)
# homo
t3 = (1,2,3,4,5)
print(t3)
# hetero
t4 = (1,2.5,True,[1,2,3])
print(t4)
# tuple
t5 = (1,2,3,(4,5))
print(t5)
()
('hello',)
<class 'tuple'>
(1, 2, 3, 4, 5)
(1, 2.5, True, [1, 2, 3])
(1, 2, 3, (4, 5))
('h', 'e', 'l', 'l', 'o')
In [ ]: print(t3)
(1, 2, 3, 4, 5)
# extract 3,4,5
print(t3[2:])
4
(3, 4, 5)
In [ ]: print(t5)
t5[-1][0]
In [ ]: print(t5)
del t5[-1]
Operation on Tuples
In [ ]: # + and *
t1 = (1,2,3,4)
t2 = (5,6,7,8)
print(t1 + t2)
# membership
print(1 in t1)
# iteration/loops
for i in t3:
print(i)
Tuple Functions
In [ ]: # len/sum/min/max/sorted
t = (1,2,3,4,5)
print(len(t))
print(sum(t))
print(min(t))
print(max(t))
print(sorted(t))
5
15
1
5
[1, 2, 3, 4, 5]
In [ ]: # count
t = (1,2,3,4,5)
t.count(3)
1
Out[ ]:
In [ ]: # index
t = (4,64567,3454,11,33,55)
t.index(64567)
1
Out[ ]:
Special Syntax
In [ ]: # tuple unpacking
a,b,c = (1,2,3)
print(a,b,c)
1 2 3
In [ ]: a = 1
b = 2
a,b = b,a
print(a,b)
2 1
In [ ]: a,b,*others = (1,2,3,4)
print(a,b)
file:///C:/Users/disha/Downloads/Day11 - Tuples In Python.html 3/5
9/30/23, 12:32 AM Day11 - Tuples In Python
print(others)
1 2
[3, 4]
In [ ]: # zipping tuples
a = (1,2,3,4)
b = (5,6,7,8)
tuple(zip(a,b))
1. Syntax:
Lists are mutable, which means you can change their elements after creation using
methods like append() , insert() , or direct assignment.
Tuples are immutable, which means once created, you cannot change their
elements. You would need to create a new tuple if you want to modify its contents.
3. Speed:
Lists are slightly slower than tuples in terms of performance because they are
mutable. Modifying a list may involve resizing or copying elements, which can
introduce overhead.
Tuples, being immutable, are generally faster for accessing elements because they
are more memory-efficient and do not require resizing or copying.
4. Memory:
Lists consume more memory than tuples due to their mutability. Lists require extra
memory to accommodate potential resizing and other internal bookkeeping.
Tuples are more memory-efficient since they don't have the overhead associated
with mutable data structures.
5. Built-in Functionality:
Both lists and tuples have common operations like indexing, slicing, and iteration.
Lists offer more built-in methods for manipulation, such as append() ,
insert() , remove() , and extend() . Lists are better suited for situations
where you need to add or remove elements frequently.
Tuples have a more limited set of operations due to their immutability but offer
security against accidental modifications.
6. Error-Prone:
Lists are typically used when you need a collection of items that can change over
time. They are suitable for situations where you want to add, remove, or modify
elements.
Tuples are used when you want to create a collection of items that should not
change during the program's execution. They provide safety and immutability.
In summary, the choice between lists and tuples depends on your specific needs. Use lists
when you require mutability and dynamic resizing, and use tuples when you want to ensure
immutability and need a more memory-efficient, error-resistant data structure.
Sets In Python
In Python, a set is an unordered collection of unique elements. Sets are used to store
multiple items, but unlike lists and tuples, they do not allow duplicate values. The elements
in a set are enclosed in curly braces '{}' and separated by commas.
Characterstics:
Unordered
Mutable
No Duplicates
Can't contain mutable data types
Creating Sets
In [ ]: # empty set
s = set()
print(s)
print(type(s))
# 1D and 2D
s1 = {1,2,3}
print(s1)
s2 = {1,2,3,(4,5)}
print(s2)
set()
<class 'set'>
{1, 2, 3}
{3, 1, (4, 5), 2}
{1, (1, 2, 3), 'hello', 4.5}
{1, 2, 3}
{1, 2, 3}
In [ ]: # True or false
s1 = {1,2,3}
s2 = {3,2,1}
print(s1 == s2)
True
Accessing Items
In Python sets, you cannot access items by indexing or slicing because sets are
unordered collections of unique elements, and they do not have a specific order like
lists or tuples. Therefore, indexing and slicing operations, which are common with
ordered sequences like lists and strings, are not applicable to sets.
Adding Items
In [ ]: #add
s = {1,2,3,4,5}
s.add(5)
print(s)
{1, 2, 3, 4, 5}
In [ ]: #update
s.update([5,6,7])
print(s)
{1, 2, 3, 4, 5, 6, 7}
Deleting Items
Sets Doesn't support item Deletion
In [ ]: # del
s= {1,2,3,4,5}
del(s)
# it complete delete set
In [ ]: # Discard
s = {1,2,3,4}
s.discard(3)
print(s)
{1, 2, 4}
In [ ]: #remove
s = {1,2,3,4}
s.remove(4)
print(s)
{1, 2, 3}
In [ ]: # pop
s.pop()
# it select random number from set
2
Out[ ]:
In [ ]: # clear
s.clear()
print(s)
set()
Set opeartion
In [ ]: s1 = {1,2,3,4,5}
s2 = {4,5,6,7,8}
# union
print(s1 | s2)
# intersection
print(s1 & s2)
# Differences
print(s1 - s2)
print(s2 - s1)
# symmetric diffrences
print(s1 ^ s2)
# membership test
print(1 in s1)
print(1 not in s1)
# iteration
for i in s1:
print(i)
{1, 2, 3, 4, 5, 6, 7, 8}
{4, 5}
{1, 2, 3}
{8, 6, 7}
{1, 2, 3, 6, 7, 8}
True
False
1
2
3
4
5
Set Function
In [ ]: # len/sum/min/max/sorted
s = {3,1,4,5,2,7}
print(len(s))
print(sum(s))
print(min(s))
print(max(s))
print(sorted(s))
In [ ]: # union/update
s1 = {1,2,3,4,5}
s2 = {4,5,6,7,8}
# s1 | s2
s1.union(s1)
s1.update(s2)
print(s1)
print(s2)
{1, 2, 3, 4, 5, 6, 7, 8}
{4, 5, 6, 7, 8}
In [ ]: # intersection/intersection_update
s1 = {1,2,3,4,5}
s2 = {4,5,6,7,8}
s1.intersection(s2)
s1.intersection_update(s2)
print(s1)
print(s2)
{4, 5}
{4, 5, 6, 7, 8}
In [ ]: # difference/difference_update
s1 = {1,2,3,4,5}
s2 = {4,5,6,7,8}
s1.difference(s2)
s1.difference_update(s2)
print(s1)
print(s2)
{1, 2, 3}
{4, 5, 6, 7, 8}
In [ ]: # symmetric_difference/symmetric_difference_update
s1 = {1,2,3,4,5}
s2 = {4,5,6,7,8}
s1.symmetric_difference(s2)
s1.symmetric_difference_update(s2)
print(s1)
print(s2)
{1, 2, 3, 6, 7, 8}
{4, 5, 6, 7, 8}
In [ ]: # isdisjoint/issubset/issuperset
s1 = {1,2,3,4}
s2 = {7,8,5,6}
s1.isdisjoint(s2)
In [ ]: s1 = {1,2,3,4,5}
s2 = {3,4,5}
s1.issuperset(s2)
True
Out[ ]:
In [ ]: # copy
s1 = {1,2,3}
s2 = s1.copy()
print(s1)
print(s2)
{1, 2, 3}
{1, 2, 3}
Frozenset
Frozen set is just an immutable version of a Python set object
In [ ]: # create frozenset
fs1 = frozenset([1,2,3])
fs2 = frozenset([3,4,5])
fs1 | fs2
frozenset({1, 2, 3, 4, 5})
Out[ ]:
Set Comprehension
In [ ]: # examples
Dictionary In Python
Dictionary in Python is a collection of keys values, used to store data values like a map,
which, unlike other data types which hold only a single value as an element.
Characterstics:
Mutable
Machine Learning Part 02:
Indexing has no meaning https://t.me/AIMLDeepThaught/689
keys can't be duplicated
keys can't be mutable items
Create Dictionary
In [ ]: # empty
d = {}
print(d)
#1D
d1 = {'name':'xyz', 'Age':23, 'gender':'male'}
print(d1)
# 2D dictionary
s = {
'name':'ramesh',
'college':'bit',
'sem':4,
'subjects':{
'dsa':50,
'maths':67,
'english':34
}
}
print(s)
Accessing Items
In [ ]: my_dict = {'name': 'Jack', 'age': 26}
my_dict['name'] # you have to write keys
'Jack'
Out[ ]:
In [ ]: d4['gender'] = 'male'
print(d4)
d4['weight'] = 70
print(d4)
# pop
d.pop(3) # it remove three
print(d)
#popitems
d.popitem() # it remove last item in the dictionary
print(d)
# del
del d['name']
print(d)
#clear
d.clear() # it clear dictionary
print(d)
In [ ]: s['subjects']['dsa'] = 80
s
{'name': 'ramesh',
Out[ ]:
'college': 'bit',
'sem': 4,
'subjects': {'dsa': 80, 'maths': 67, 'english': 34}}
Dictionary Operations
Membership
Iteration
In [ ]: print(s)
In [ ]: # membership
'name' in s
True
Out[ ]:
False
Out[ ]:
In [ ]: # ITERATION
for i in s:
print(i,s[i])
name ramesh
college bit
sem 4
subjects {'dsa': 80, 'maths': 67, 'english': 34}
Dictionary Functions
In [ ]: print(s)
In [ ]: # len/sorted
print(len(s))
sorted(s)
4
['college', 'name', 'sem', 'subjects']
Out[ ]:
In [ ]: # items/keys/values
print(s.items())
print(s.keys())
print(s.values())
In [ ]: # update
d1 = {1:2,3:4,4:5}
d2 = {4:7,6:8}
d1.update(d2)
print(d1)
{1: 2, 3: 4, 4: 7, 6: 8}
Dictionary Comprehension
In [ ]: # print 1st 10 numbers and their squares
{i:i**2 for i in range(1,11)}
In [ ]: distances = {'delhi':1000,'mumbai':2000,'bangalore':3000}
print(distances.items())
In [ ]: # using zip
days = ["Sunday", "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
temp_C = [30.5,32.6,31.8,33.4,29.8,30.2,29.9]
{'Sunday': 30.5,
Out[ ]:
'Monday': 32.6,
'Tuesday': 31.8,
'Wednesday': 33.4,
Machine Learning Part 02:
'Thursday': 29.8,
'Friday': 30.2,
https://t.me/AIMLDeepThaught/689
'Saturday': 29.9}
In [ ]: # using if condition
products = {'phone':10,'laptop':0,'charger':32,'tablet':0}
In [ ]: # Nested Comprehension
# print tables of number from 2 to 4
{i:{j:i*j for j in range(1,11)} for i in range(2,5)}
OOP in Python
(Object-Oriented Programming)
1. Python Class
A class is a collection of objects. A class contains the blueprints or the prototype from
which the objects are being created. It is a logical entity that contains some attributes
and methods.
To understand the need for creating a class let’s consider an example, let’s say you wanted
to track the number of dogs that may have different attributes like breed, and age. If a list is
used, the first element could be the dog’s breed while the second element could represent
its age. Let’s suppose there are 100 different dogs, then how would you know which
element is supposed to be which? What if you wanted to add other properties to these
dogs? This lacks organization and it’s the exact need for classes.
In [ ]: class ClassName:
# Statement-1
.
.
class Dog:
pass
2. Python Objects
The object is an entity that has a state and behavior associated with it. It may be any
real-world object like a mouse, keyboard, chair, table, pen, etc. Integers, strings,
floating-point numbers, even arrays, and dictionaries, are all objects.
More specifically, any single integer or any single string is an object. The number 12 is
an object, the string “Hello, world” is an object, a list is an object that can hold other
objects, and so on. You’ve been using objects all along and may not even realize it.
In [ ]: obj = Dog()
In [ ]: class mynumber:
def __init__(self, value):
self.value = value
def print_value(self):
print(self.value)
obj1 = mynumber(17)
obj1.print_value()
17
and set its attributes. By following these guidelines, you can create powerful and efficient
classes in Python.
In [ ]: # _init_
class Subject:
Maths
Science
1. Function:
A function is a block of organized, reusable code that performs a specific task.
Functions in Python are defined using the def keyword, followed by a function name, a
set of parameters in parentheses, a colon, and the function's code block.
Functions can take input parameters (arguments) and return a value using the return
statement. However, not all functions need to return a value.
Functions can be called by their name, and they are usually defined at the module level
(i.e., not inside a class or another function).
2. Method:
A method is similar to a function, but it is associated with an object or a class.
Methods are defined within a class and are used to define the behaviors or actions that
objects of that class can perform.
Methods are called on instances of a class and typically operate on the data (attributes)
of the instance.
The first parameter of a method is usually named 'self', which refers to the instance on
which the method is called.
In summary, functions are standalone blocks of code, while methods are functions defined
within a class and are associated with instances of that class. Methods often work with the
data (attributes) of the instance, whereas functions can be called independently of any
specific object or class.
In [ ]: # _init_
class Subject:
Magic Methods:
In Python, "magic methods," also known as "dunder methods" (short for "double underscore
methods"), are special methods that have double underscores at the beginning and end of
their names, such as _ init , str , add _ , etc. These methods are also sometimes referred to as
"special methods" or "dunder methods" because of their naming convention.
Magic methods are used to define how objects of a class behave in various situations and
allow you to customize the behavior of your custom classes. They are automatically invoked
by the Python interpreter in response to specific operations or built-in functions.
1. init :
The _ init _ method in Python is like a special function that gets called when you create
a new object from a class.
It's often referred to as the "constructor" because it helps you set up, or "initialize," the
initial state of an object.
In [ ]: print(person1)
when we print person 1 then python don't know how to show Alice with age 30
..python show only Memory location where it store
so for we call str
2. str :
The str method in Python is a special method (often called a "magic method" or
"dunder method") that you can define in your custom classes to provide a human-
readable string representation of objects created from that class.
This method is automatically called when you use the str() function or the print()
function on an object.
In [ ]: class Person:
def __init__(self, name, age):
self.name = name
self.age = age
In [ ]: class Point:
def __init__(self,x,y):
self.x_cod = x
self.y_cod = y
def __str__(self):
return "<{},{}>".format(self.x_cod,self.y_cod)
In [ ]: x = 4
y = 5
print(Point(4,5))
<4,5>
In [ ]: class Point:
def __init__(self,x,y):
self.x_cod = x
self.y_cod = y
def __str__(self):
return "<{},{}>".format(self.x_cod,self.y_cod)
def euclidean_distance(self,other):
return ((self.x_cod-self.y_cod)**2 + (self.y_cod-self.x_cod)**2)**0.5
In [ ]: p1 = Point(0,1)
p2 = Point(1,1)
p1.euclidean_distance(p2)
1.4142135623730951
Out[ ]:
In [ ]: class Point:
def __init__(self,x,y):
self.x_cod = x
self.y_cod = y
file:///C:/Users/disha/Downloads/Day16 - OOP in Python(Part3).html 1/2
10/5/23, 10:14 AM Day16 - OOP in Python(Part3)
def distance_from_origin(self):
return (self.x_cod**2 + self.y_cod**2)**0.5
In [ ]: p1 = Point(0,10)
p2 = Point(1,10)
print(p1.distance_from_origin())
print(p2.distance_from_origin())
10.0
10.04987562112089
In [ ]: class Line:
def __init__(self,A,B,C):
self.A = A
self.B = B
self.C = C
def __str__(self):
return '{}x + {}y + {} = 0'.format(self.A, self.B, self.C)
def point_on_line(line,point):
if line.A*point.x_cod + line.B*point.y_cod + line.C == 0:
return 'point lies on line'
else:
return 'does not on line'
In [ ]: l1 = Line(1,1,-2)
p1 = Point(1,10)
l1.point_on_line(p2)
In [ ]: class Line:
def __init__(self,A,B,C):
self.A = A
self.B = B
self.C = C
def shortest_distance(line,point):
return abs(line.A*point.x_cod + line.B*point.y_cod + line.C)/(line.A**2 + line.
In [ ]: l1 = Line(1,1,-2)
p1 = Point(1,10)
l1.shortest_distance(p1)
6.363961030678928
Out[ ]:
1. Public: Attributes and methods that are accessible from outside the class without any
restrictions. By default, all attributes and methods in Python are public.
2. Protected: Attributes and methods that are intended to be used only within the class
and its subclasses. In Python, you can denote a protected attribute or method by
prefixing it with a single underscore (e.g., _my_attribute ).
3. Private: Attributes and methods that are intended to be used only within the class. In
Python, you can denote a private attribute or method by prefixing it with a double
underscore (e.g., __my_attribute ).
class Myclass:
def __init__(self):
self.public_attribute = 55
self._protected_attribute = 'Hello'
self.__private_attribute = 'World'
def public_method(self):
return "This is public method"
def _protected_method(self):
return "This is Protected Method"
def __private_method(self):
return "this is private Method"
In [ ]: obj = Myclass()
In [ ]: # we have to access the public attribaute dirctly and don't give any tyoe of error
print(obj.public_attribute)
print(obj.public_method())
55
This is public method
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
c:\Users\disha\Downloads\Pythoon 100 Days\100_Days_OF_Python\Day17 - Encapsulation
in OOP in Python.ipynb Cell 7 line 2
<a href='vscode-notebook-cell:/c%3A/Users/disha/Downloads/Pythoon%20100%20Da
ys/100_Days_OF_Python/Day17%20-%20Encapsulation%20in%20OOP%20in%20Python.ipynb#W6s
ZmlsZQ%3D%3D?line=0'>1</a> # Accessing private attributes and methods directly wil
l result in an error:
----> <a href='vscode-notebook-cell:/c%3A/Users/disha/Downloads/Pythoon%20100%20Da
ys/100_Days_OF_Python/Day17%20-%20Encapsulation%20in%20OOP%20in%20Python.ipynb#W6s
ZmlsZQ%3D%3D?line=1'>2</a> print(obj.__private_attribute) # Raises an AttributeE
rror
<a href='vscode-notebook-cell:/c%3A/Users/disha/Downloads/Pythoon%20100%20Da
ys/100_Days_OF_Python/Day17%20-%20Encapsulation%20in%20OOP%20in%20Python.ipynb#W6s
ZmlsZQ%3D%3D?line=2'>3</a> print(obj.__private_method())
In a bustling city, there was a high-tech security system protecting a valuable treasure. The
system had a keypad (public interface) that allowed authorized personnel to enter a secret
code. Behind the keypad was a locked room (protected layer) with advanced security
features, and inside that room was a safe (private layer) holding the treasure. Only a select
few knew the secret code, ensuring the treasure's safety while providing access to those who
needed it. This is encapsulation in action, safeguarding valuable data while allowing
controlled access.
3. Information Hiding: It hides complex internal details, reducing the complexity for
users of a class and allowing developers to change the implementation without
impacting external code.
3. Code Organization: Encapsulation helps organize code by bundling related data and
methods within a class. This modular approach enhances code readability and
maintainability, making it easier to manage large codebases.
4. Security: By encapsulating sensitive data and operations, you can control who has
access to them. This enhances security by preventing unauthorized access or
manipulation of critical information.
These two class relationships, inheritance and aggregation, are fundamental concepts in
OOP and are used extensively in software design to model different types of relationships
between classes and objects.
1. Aggregation(Has a Realtionship)
In object-oriented programming (OOP) with Python, aggregation is a type of association
between classes where one class, known as the "container" or "composite" class, contains or
references another class, known as the "contained" or "component" class. Aggregation
represents a "has-a" relationship, where the container class has one or more instances of the
contained class as part of its own structure.
Aggregation is often used to model relationships between objects when one object is
composed of or contains other objects. It is a way to create more complex objects by
combining simpler objects. A classic example of aggregation is a university system where a
University class can contain Department objects, and each Department can contain
`Professor objects.
In [ ]: class Professor:
def __init__(self, name):
self.name = name
class Department:
def __init__(self, name):
self.name = name
self.professors = [] # Aggregation: Department contains Professor objects
class University:
def __init__(self, name):
self.name = name
self.departments = [] # Aggregation: University contains Department object
# Creating objects
professor1 = Professor("John Doe")
professor2 = Professor("Jane Smith")
In this example:
Aggregation is a way to represent the idea that one class is composed of or contains
instances of another class, and it is often used to model real-world relationships between
objects in a system.
The solid diamond indicates Composition. Notice how teams belong to the single
company object. If the company object is deleted, the teams will have no reason to exist
anymore.
The open diamond indicates Aggregation. When a team is deleted, the employees that
were in the team, still exist. Employees might also belong to multiple teams. A team
object does not "own" an employee object.
Inheritance in OOP
Inheritance is typically used to model an "is-a" relationship between classes, where the
derived class is a more specific or specialized version of the base class. The derived class
inherits the attributes and methods of the base class and can also have its own additional
attributes and methods or override the inherited ones.
In [ ]: class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass # Base class method, to be overridden by subclasses
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
# Creating objects
dog = Dog("Buddy")
cat = Cat("Whiskers")
In this example:
'Animal' is the base class, and 'Dog' and 'Cat' are subclasses of 'Animal'.
Both 'Dog' and 'Cat' inherit the 'name' attribute and the 'speak' method from the
'Animal' class.
However, each subclass overrides the 'speak' method to provide its own
implementation, representing the specific behavior of each animal. Inheritance is a
powerful mechanism in OOP because it allows you to create a hierarchy of classes, with
each level of the hierarchy adding or modifying functionality as needed. This promotes
code reuse, encapsulation, and abstraction, making it easier to manage and extend your
codebase.
4. Supports Code Extensibility: With inheritance, you can extend existing classes to add
or modify functionality. Derived classes can override inherited methods to provide
specialized behavior while still benefiting from the base class's shared attributes and
methods. This makes it straightforward to adapt and extend your code to
accommodate changing requirements.
Inheritance in summary
Child class can override the attributes or methods. This is called method overriding
super() is an inbuilt function which is used to invoke the parent class methods and
constructor
Types of Inheritance
1. Single Inheritance:
In single inheritance, a class inherits properties and behaviors from a single parent
class. This is the simplest form of inheritance, where each class has only one
immediate base class.
2. Multilevel Inheritance:
In multilevel inheritance, a class derives from a class, which in turn derives from
another class. This creates a chain of inheritance where each class extends the
previous one. It forms a hierarchy of classes.
3. Hierarchical Inheritance:
Multiple inheritance occurs when a class inherits properties and behaviors from
more than one parent class. This can lead to a complication known as the
"diamond problem," where ambiguity arises when a method or attribute is called
that exists in multiple parent classes. Some programming languages, like Python,
provide mechanisms to resolve this ambiguity.
5. Hybrid Inheritance:
These different types of inheritance allow developers to model various relationships and
structures in object-oriented programming. Choosing the appropriate type of inheritance
depends on the specific requirements and design of the software being developed.
In [ ]: # single inheritance
class Phone:
def __init__(self, price, brand, camera):
def buy(self):
print ("Buying a phone")
class SmartPhone(Phone):
pass
SmartPhone(1000,"Apple","13px").buy()
In [ ]: # multilevel
class Product:
def review(self):
print ("Product customer review")
class Phone(Product):
def __init__(self, price, brand, camera):
print ("Inside phone constructor")
self.__price = price
self.brand = brand
self.camera = camera
def buy(self):
print ("Buying a phone")
class SmartPhone(Phone):
pass
In [ ]: # Hierarchical
class Phone:
def __init__(self, price, brand, camera):
print ("Inside phone constructor")
self.__price = price
self.brand = brand
self.camera = camera
def buy(self):
print ("Buying a phone")
class SmartPhone(Phone):
pass
In [ ]: # Multiple
class Phone:
def __init__(self, price, brand, camera):
print ("Inside phone constructor")
self.__price = price
self.brand = brand
self.camera = camera
def buy(self):
print ("Buying a phone")
class Product:
def review(self):
print ("Customer review")
Polymorphism:
Polymorphism is one of the four fundamental principles of Object-Oriented Programming
(OOP), along with encapsulation, inheritance, and abstraction. It allows objects of different
classes to be treated as objects of a common superclass. In Python, polymorphism is
implemented through method overriding and method overloading, which are two related
concepts.
1. Method Overriding
2. Method Overloading
1. Method Overriding
Method overriding occurs when a subclass provides a specific implementation of a method
that is already defined in its superclass. This allows the subclass to provide its own behavior
for a method while still adhering to the method signature defined in the superclass.
In [ ]: class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
dog = Dog()
cat = Cat()
print(dog.speak())
print(cat.speak())
Woof!
Meow!
2.Method Overloading:
Method overloading allows a class to define multiple methods with the same name but
different parameters. Python does not support traditional method overloading with different
parameter types like some other languages (e.g., Java or C++). Instead, Python achieves a
form of method overloading using default arguments and variable-length argument lists.
Here's an example:
In [ ]: class Calculator:
def add(self, a, b):
return a + b
calc = Calculator()
#result1 = calc.add(1, 2) # Error: The second add method with three paramete
result2 = calc.add(1, 2, 3) # This works fine.
In Python, only the latest defined method with a particular name is accessible. Traditional
method overloading with different parameter types isn't supported.
In [ ]: class Shape:
def area(self,a,b=0):
if b == 0:
return 3.14*a*a
else:
return a*b
s = Shape()
print(s.area(2))
print(s.area(3,4))
12.56
12
Polymorphism allows you to write more flexible and reusable code by treating different
objects in a consistent way, regardless of their specific class. This promotes code flexibility
and makes it easier to extend and maintain your programs as they grow in complexity.
Abstraction
Abstraction is one of the four fundamental principles of Object-Oriented Programming
(OOP), along with encapsulation, inheritance, and polymorphism. Abstraction is the process
of simplifying complex reality by modeling classes based on the essential properties and
behaviors of objects, while ignoring or hiding the non-essential details.
1. Modeling: Abstraction involves defining classes and objects that capture the essential
characteristics and behaviors of real-world entities or concepts. You create classes to
represent these abstractions, defining their attributes (data) and methods (behavior) to
interact with them.
2. Hiding Complexity: Abstraction allows you to hide the internal details and
complexities of an object's implementation from the outside world. This is achieved
through encapsulation, where you define private attributes and provide public methods
to interact with the object.
4. Focus on What, Not How: When you work with abstractions, you can focus on using
objects based on what they do (their methods) rather than how they do it (their
implementation details). This separation of concerns simplifies the design and
maintenance of complex systems.
In [ ]: class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
def start(self):
pass
def stop(self):
pass
class Car(Vehicle):
def start(self):
print(f"{self.make} {self.model} is starting")
def stop(self):
print(f"{self.make} {self.model} is stopping")
class Motorcycle(Vehicle):
def start(self):
print(f"{self.make} {self.model} is revving up")
def stop(self):
print(f"{self.make} {self.model} is slowing down")
In this example, the Vehicle class represents an abstraction of a general vehicle with
common attributes (make and model) and methods (start and stop). Concrete subclasses
like Car and Motorcycle inherit from Vehicle and provide specific implementations
for the start and stop methods. Users of these classes can interact with them without
needing to know the exact implementation details of each vehicle type.
Abstraction helps in managing complexity, improving code organization, and making code
more maintainable and understandable by focusing on high-level concepts and behaviors.
@abstractmethod
def display(self):
pass
In [ ]: class MobileApp(BankApp):
def mobile_login(self):
print('login into mobile')
def display(self):
print('display')
In [ ]: mob = MobileApp()
In [ ]: mob.security()
mobile security
In [ ]: obj = BankApp()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
c:\Users\disha\Downloads\Pythoon 100 Days\100_Days_OF_Python\Polymorphism and Abst
raction - Object-Oriented Programming (OOP).ipynb Cell 19 line 1
----> <a href='vscode-notebook-cell:/c%3A/Users/disha/Downloads/Pythoon%20100%20Da
ys/100_Days_OF_Python/Polymorphism%20and%20Abstraction%20-%20Object-Oriented%20Pro
gramming%20%28OOP%29.ipynb#X26sZmlsZQ%3D%3D?line=0'>1</a> obj = BankApp()
TypeError: Can't instantiate abstract class BankApp with abstract methods display,
security
The error message indicates that you are trying to instantiate an abstract class called
BankApp, but this class contains abstract methods display and security that have not been
implemented in the BankApp class or its subclasses.
In Python, an abstract class is a class that cannot be instantiated directly, and it often serves
as a blueprint for other classes. Abstract classes can contain abstract methods, which are
methods declared without an implementation in the abstract class. Subclasses of the
abstract class are required to provide implementations for these abstract methods.