Python Updated [Autosaved]
Python Updated [Autosaved]
Note:
‘0’ indicates absence of electrical pulse
‘1’ indicates presence of electrical pulse.
Three Types Of Translators Are There
For Example, ADD, MUL, DIV, SUB, START, STOP, LABEL Etc.
1. AI
2. Machine learning
3. Data Analytics
4. Data visualisation
5. Web development
6. Game development
7. Programming application
8. Language development
9. Search Engine optimisation
10.Finance
LANGUAGE FEATURES
Interpreted
There are no separate compilation and execution steps like C and C++.
Directly run the program from the source code.
Internally, Python converts the source code into an intermediate form
called bytecodes which is then translated into native language of
specific computer to run it.
No need to worry about linking and loading with libraries, etc.
Platform Independent
Python programs can be developed and executed on multiple
operating system platforms.
Python can be used on Linux, Windows, Macintosh, Solaris and many
more.
Free and Open Source :- Redistributable
LANGUAGE FEATURES
High-level Language
In Python, no need to take care about low-level details
such as managing the memory used by the program.
Robust:
Exceptional handling features
Memory management techniques in built
LANGUAGE FEATURES
JAVA PYTHON
1.it is fast and secure general purpose 1.A readable, efficient and powerful highlevel
programming language programming language
2.it is statically typed 2.it is dynamically typed
3.longer lines of code when compared to python 3.shorter lines of code when compared to java
4.most popular and widely used databases 4.Access layers are weaker than java JDBC
5.popular for mobile and web applications 5.Popular for data science , ML, AI, IOT
Interpreter Compiler
Translates program’s one statement at a Scans the entire program and translates it
time. as a whole into machine code.
Interpreters usually take less amount of Compilers usually take a large amount of
time to analyze the source code. However, time to analyze the source code. However,
the overall execution time is the overall execution time is
comparatively slower than compilers. comparatively faster than interpreters.
Generates Object Code which further
No Object Code is generated, hence are
requires linking, hence requires more
memory efficient.
memory.
Programming languages like JavaScript, Programming languages like C, C++, Java
Python, Ruby use interpreters. use compilers.
Statically Typed vs Dynamically typed
Basic things about Python
Python keywords :- They are special reserved words that have specific
meanings and purposes and can't be used for anything but those specific
purposes.
True, False, None, and, as, assets ,
def, class, continue, break, else,
finally, elif, del, except, global, for ,
if, from, import, raise, try, or, return,
pass, nonlocal, in, not, is ,lambda
Basic things about Python
Example:
id=123
print(id)
123
name=“Arunpal"
There are 3 types of variable declaration:
Examples:
a=b=c=45
print(a)
print(c)
print(c)
output >45
There are 3 types of variable declaration:
Example:
>>> a ,b ,c =11,12,13
Data Types:
Numeric type:-
There are three numeric types in Python:
Int, float, complex
x = 1 # int
y = 2.8 # float
z = 1j # complex
DATA TYPES:-
String type
Strings in python are surrounded by either single quotation
marks, or double quotation marks.
Single line string.
Multi line string.
AND IT CAN BR OF ANY DATA TYPE INSIDE THE
QUOTATION
Type:-‘str’
Ex: a=“Arunpal”
b=“ WELCOME TO Besant Technologies FREE
PYTHON CLASSES
@ Indiranagar BANGALORE”
DATA TYPES:-
LIST
Lists are used to store multiple items in a single variable.
Lists are created using square brackets:
Allows duplicates
Ex: a=[] # empty list
b=[1,1.2, “python class”,[1,2,3]]
DATA TYPES:-
Tuples
Tuples are used to store multiple items in a single variable.
Tuples are written with round brackets.
Dictonary
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not
allow duplicates.
Ex: a={} # empty dict
b={“name”: “Rocky”,
“movie”: [“KGF 1”, “KGF 2”]
}
Data types:-
Python Casting:-
Specify a Variable Type
Casting in python is therefore done using constructor functions:
INTEGER:- Constructs an integer number from an integer literal, a float literal (by
removing all decimals), or a string literal (providing the string represents a whole
number)
FLOAT:- Constructs a float number from an integer literal, a float literal or a string literal
(providing the string represents a float or an integer)
STRING:-constructs a string from a wide variety of data types, including strings, integer
literals and float literals
Operators
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
Membership Operators
Bitwise Operators
Identity Operators
Operators
Examples:-
val1 = 2
val2 = 3
# using the addition operator
res = val1 + val2
print(res)
# using the multiplication operator
res = val1 * val2
print(res)
Operators
Add and Assign: Add right side operand with left side
+= a += b
operand and then assign to left operand
# Assign value
b=a
print(b)
Comparison Operators are used for comparing the values. It either returns True or False
according to the condition.
Operator Description Syntax
> Greater than: True if the left operand is greater than the right x>y
< Less than: True if the left operand is less than the right x<y
Logical operators are used on conditional statements (either True or False). They
perform Logical AND, Logical OR and Logical NOT operations.
Membership Operators
in and not in are the membership operators; used to test whether a value or variable is in a
sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence
Operators
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
Operators
Bitwise operators
In Python, bitwise operators are used to performing bitwise
calculations on integers. The integers are first converted into
binary and then operations are performed on bit by bit, hence
the name bitwise operators. Then the result is returned in
decimal format.
| Bitwise OR x|y
~ Bitwise NOT ~x
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
a & b = 1010 & 0100
= 0000
= 0 (Decimal)
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
a | b = 1010 | 0100
= 1110
= 14 (Decimal)
Operators
a = 10 = 1010 (Binary)
~a = ~1010
= -(1010 + 1)
= -(1011)
= -11 (Decimal)
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
a ^ b = 1010 ^ 0100
= 1110
= 14 (Decimal)
Operators
Identity Operators
is and is not are the Identity Operators both are used to check
if two values are located on the same part of the memory. Two
variables that are equal do not imply that they are identical
print(a is not b)
print(a is c)
If statements
if statement:-
if statement is the most simple decision-making statement. It is used to
decide whether a certain statement or block of statements will be executed
or not i.e if a certain condition is true then a block of statement is executed
otherwise not.
Syntax:-
if condition:
# Statements to execute if
# condition is true
If-else Statements
if-else
The if statement alone tells us that if a condition is true it will execute
a block of statements and if the condition is false it won’t. But what if
we want to do something else if the condition is false. Here comes
the else statement. We can use the else statement with if statement to
execute a block of code when the condition is false.
Syntax:-
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
if- elif -else ladder
if-elif-else ladder
The if statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with that if is
executed, and the rest of the ladder is bypassed. If none of the conditions is
true, then the final else statement will be executed.
Syntax:
if condition1:
# Block of code to execute if condition1 is true
elif condition2:
# Block of code to execute if condition2 is true
else:
# Block of code to execute if all conditions are false
Nested-if
Nested-if
A nested if is an if statement that is the target of another if
statement. Nested if statements mean an if statement inside
another if statement. Yes, Python allows us to nest if statements
within if statements. i.e, we can place an if statement inside
another if statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
While Loops
With the break statement we can stop the loop even if the
while condition is true.
Write a program to check if any number is divisible by 3 in
between 25 to 35.
i = 25
while i < 36:
print(i)
if i %3== 0:
break
i += 1
Continue Statement with while loop
With the else statement we can run a block of code once when
the condition no longer is true:
Example
Print a message once the condition is false:
i=1
while i < 11:
print(i)
i += 1
else:
print("i is no longer less than 11")
For loop
Note: The else block will NOT be executed if the loop is stopped by
a break statement.
Else in For Loop
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
Python Nested for Loop
code reusability
reducing duplication of code
decomposing complex problems into smaller pieces.
abstraction
Syntax:
def <function_name>(Parameters):
statements
…………………..
return statement
‘def’ is a keyword used to define a function
‘def’ keyword is followed by a function name
function can contain parameters or without parameters.
return statement is optional
the return statement is used to return the value.
A function can have only one return.
by using return statement we can return multiple values.
Function calling:
def my_function(*args):
for i in args:
print(i)
my_function(1, 2, 3, 4)
Variable-length keyword arguments.
def my_function(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
my_function(name="Alice", age=30, city="New York")
Local variables
Syntax:
lambda arguments: expression
Why Use Lambda Functions?
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the
specified value
extend() Add the elements of a list (or any iterable), to
the end of the current list
List methods
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Tuple Methods
Method Description
count() Returns the number of times a specified value
occurs in a tuple
index() Searches the tuple for a specified value and
returns the position of where it was found
Dictionary Methods
Method Description
capitalize() Converts the first character to upper case
endswith() Returns true if the string ends with the
specified value
count() Returns the number of times a specified value
occurs in a string
String Methods
add(): Adds an element to the set. If the element is already present, it doesn't add
it again.
clear(): Removes all the elements from the set, making it an empty set.
copy(): Returns a shallow copy of the set.
difference(): Returns a new set containing elements that are present in the first set
but not in the second set(s).
difference_update(): Updates the set, removing elements that are present in other
specified set(s).
discard(): Removes the specified element from the set if it is present.
intersection(): Returns a new set containing elements that are common to both
sets.
Set methods
f-strings are string literals that have an f at the beginning and curly braces
containing expressions that will be replaced with their values.
Python string format() function has been introduced for handling complex
string formatting more efficiently. Sometimes we want to make generalized
print statements in that case instead of writing print statement every time we
use the concept of formatting.
# using format function
print("My Name is {} and I am {} years old".format(name,age))
Formating ways:-
# using f_string
print(f"Hello, My name is {name} and I'm {age} years old.")
Formating ways:-
mystring = “Rajnikanta”
s1 = slice(3)
s2 = slice(1, 5, 2)
s3 = slice(-1, -8, -2)
# s4=slice(1,6,-2) # cannot give negative value here
# s4=slice(-2,-7,2) # cannot give positive value here
s4=slice(-8,6)
String sclicing
print(mystring[6:-7:-1])
print(mystring[7:2:-2])
print(mystring[:-7]) # 0 to -8
print(mystring[:]) # copy of the string
print(mystring[4:])
print(mystring[:-1])
print(mystring[::-1])
Module
The module is a simple Python file that contains collections of functions and global
variables and with having a .py extension file.
It is an executable file and to organize all the modules we have the concept called
Package in Python.
A module is a single file (or files) that are imported under one
import and used. E.g. import mymodule
Package
numpy: Provides support for large, multi-dimensional arrays and matrices, along with a collection of
mathematical functions to operate on these arrays.
pandas: Offers data structures and data analysis tools for working with structured data, such as tables
and time series.
matplotlib: Allows creation of static, animated, and interactive visualizations in Python.
requests: Simplifies making HTTP requests in Python.
scikit-learn: Offers machine learning algorithms and tools for data mining and data analysis.
tensorflow: An open-source machine learning library for high-performance numerical computation
and deep learning.
django: A high-level Python web framework for building web applications.
flask: A lightweight web framework for building web applications and APIs.
beautifulsoup4: A library for scraping information from web pages.
sqlalchemy: A SQL toolkit and Object-Relational Mapping (ORM) library for Python.
Python Datetime
NumPy, short for Numerical Python, is a fundamental
package for numerical computing in Python. It provides
support for large, multi-dimensional arrays and matrices,
along with a collection of mathematical functions to operate
on these arrays efficiently. NumPy is a core library for
scientific computing in Python and is widely used in fields
such as data science, machine learning, engineering, and
scientific research.
Key features of NumPy include:
Multi-dimensional Arrays: NumPy's main object is the ndarray, which is a multidimensional array of elements of the same type. These arrays can
be of any dimensionality, allowing for efficient storage and manipulation of large datasets.
Array Operations: NumPy provides a wide range of mathematical functions that operate element-wise on arrays, including arithmetic operations,
trigonometric functions, exponential and logarithmic functions, statistical functions, and more. These operations are optimized for performance,
making them suitable for large-scale numerical computations.
Broadcasting: NumPy allows for arithmetic operations between arrays of different shapes and sizes through broadcasting. Broadcasting
automatically aligns the dimensions of arrays to perform element-wise operations, which simplifies the code and improves efficiency.
Indexing and Slicing: NumPy offers powerful indexing and slicing capabilities for accessing and manipulating elements of arrays. It supports
advanced indexing techniques such as boolean indexing, integer array indexing, and fancy indexing.
Vectorized Computations: NumPy encourages vectorized computations, where operations are applied to entire arrays at once, rather than looping
over individual elements. This approach leads to faster execution times and cleaner code compared to traditional looping constructs.
Random Number Generation: NumPy includes a random number generation module (numpy.random) for generating random numbers from
various probability distributions. This module is useful for tasks such as simulation, modeling, and statistical analysis.
Integration with Other Libraries: NumPy integrates seamlessly with other scientific computing libraries in Python, such as SciPy, Matplotlib,
Pandas, and Scikit-learn, enabling a cohesive ecosystem for data analysis, visualization, and machine learning.
Why Use NumPy?
import numpy
NumPy as np
alias: In Python alias are an alternate name for referring to the same
thing.
import numpy as np
Now the NumPy package can be referred to as np instead of numpy.
Create a NumPy ndarray Object
NumPy is used to work with arrays. The array object in NumPy is called
ndarray.
print(arr)
print(type(arr))
Ndarray ,Ndim
type(): This built-in Python function tells us the type of the object
passed to it. Like in above code it shows that arr is numpy.ndarray
type.
import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
NumPy Array Indexing
import numpy as np
print(arr[2] + arr[3])
Indexing – 2d
import numpy as np
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2])
Array Slicing
Slicing arrays
Slicing in python means taking elements from one given index to another given index.
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5:2])
Slicing 2-D Arrays
import numpy as np
print(arr[1, 1:4])
Data Types
i - integer
b - boolean
u - unsigned integer
f - float
c - complex float
m - timedelta
M - datetime
O - object
S - string
U - unicode string
V - fixed chunk of memory for other type ( void )
Checking the Data Type of an Array
import numpy as np
print(arr.dtype)
import numpy as np
print(arr.dtype)
Creating Arrays With a Defined Data Type
import numpy as np
arr = np.array([1, 2, 3, 4], dtype='S')
print(arr)
print(arr.dtype)
Converting Data Type on Existing Arrays
import numpy as np
newarr = arr.astype('i')
print(newarr)
print(newarr.dtype)
2nd way
import numpy as np
newarr = arr.astype(int)
print(newarr)
print(newarr.dtype)
NumPy Array Copy vs View
import numpy as np
print(arr)
print(x)
The copy SHOULD NOT be affected by the changes
made to the original array.
VIEW:
import numpy as np
print(arr)
print(x)
The view SHOULD be affected by the changes made to the
original array.
Check if Array Owns its Data
import numpy as np
x = arr.copy()
y = arr.view()
print(x.base)
print(y.base)
The copy returns None.
The view returns the original array.
Array Shape
import numpy as np
import numpy as np
print(arr)
print('shape of array :', arr.shape)
Reshaping
Reshaping arrays
Reshaping means changing the shape of an array.
The shape of an array is the number of elements in each dimension.
By reshaping we can add or remove dimensions or change number
of elements in each dimension.
Reshape From 1-D to 2-D
import numpy as np
newarr = arr.reshape(4, 3)
print(newarr)
Unknown Dimension
print(newarr)
Flattening the arrays
newarr = arr.reshape(-1)
print(newarr)
Iterating Arrays
for x in arr:
print(x)
Iterating 2-D Arrays
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
for x in arr:
print("x represents the 2-D array:")
print(x)
Iterating Arrays Using nditer()
import numpy as np
for x in np.nditer(arr):
print(x)
Joining NumPy Arrays
print(arr)
Joining with axis
import numpy as np
print(arr)
Stacking Along Rows
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.hstack((arr1, arr2))
print(arr)
Stacking Along Columns
import numpy as np
print(arr)
Splitting NumPy Arrays
newarr = np.array_split(arr, 3)
print(newarr)
The return value is a list containing three arrays.
import numpy as np
newarr = np.array_split(arr, 4)
print(newarr)
We also have the method split() available but it will not adjust the
elements when elements are less in source array for splitting like
in example above, array_split() worked properly but split() would
fail.
Split Into Arrays
The return value of the array_split() method is an array containing each of the split
as an array.
If you split an array into 3 arrays, you can access them from the result just like any
array element:
import numpy as np
newarr = np.array_split(arr, 3)
print(newarr[0])
print(newarr[1])
print(newarr[2])
Splitting 2-D Arrays
import numpy as np
arr = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]])
newarr = np.array_split(arr, 3)
print(newarr)
hsplit() opposite of hstack()
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]])
newarr = np.hsplit(arr, 3)
print(newarr)
You can search an array for a certain value, and return the indexes that get a match.
To search an array, use the where() method.
import numpy as np
x = np.where(arr == 4)
print(x)
x = np.where(arr%2 == 0)
print(x)
Search Sorted
There is a method called searchsorted() which performs a binary search in the array, and
returns the index where the specified value would be inserted to maintain the search order.
The searchsorted() method is assumed to be used on sorted arrays.
import numpy as np
x = np.searchsorted(arr, 7)
print(x)
Sorting Arrays
import numpy as np
print(np.sort(arr))
This method returns a copy of the array, leaving the original array
unchanged.
Sorting a 2-D Array
import numpy as np
print(np.sort(arr))
Filtering Arrays
DataFrame: Pandas introduces the DataFrame data structure, which is a two-dimensional, size-mutable, and
heterogeneous tabular data structure with labeled axes (rows and columns). It allows you to store and manipulate data in a
way similar to a spreadsheet or SQL table.
Series: Along with DataFrame, Pandas also provides the Series data structure, which is a one-dimensional labeled array
capable of holding any data type.
Data Manipulation: Pandas offers a wide range of functions and methods for data manipulation, including indexing,
slicing, filtering, sorting, merging, joining, reshaping, grouping, aggregating, and pivoting data.
Data Cleaning: Pandas provides tools for handling missing data, converting data types, removing duplicates, and
performing other data cleaning tasks.
Data Input/Output: Pandas supports various file formats for importing and exporting data, including CSV, Excel, SQL
databases, JSON, HTML, and more..
Integration with Other Libraries: Pandas integrates well with other Python libraries such as NumPy, Matplotlib,
Seaborn, and Scikit-learn, providing seamless interoperability for data analysis, visualization, and machine learning tasks.
Series
CSV files are text files with information separated by commas, saved with the
extension .csv. They allow large amounts of detailed data to be transferred ‘machine-to-
machine’, with little or no reformatting by the user.
You can open a CSV file with any spreadsheet, statistics, or analysis program, such as
Microsoft Excel, the R statistical environment, or Python.
CSV files may open in Excel by default, but they are not designed as Excel files. If CSV
files are opened in Excel, certain information (eg codes with leading zeros) could be
missing. Ideally, they should be
If you have a large DataFrame with many rows, Pandas will only return the first 5 rows,
and the last 5 rows
use to_string() to print the entire DataFrame.
The number of rows returned is defined in Pandas option settings.
You can check your system's maximum rows with
the pd.options.display.max_rows statement.
In my system the number is 60, which means that if the DataFrame contains more than 60
rows, the print(df) statement will return only the headers and the first and last 5 rows.
You can change the maximum rows number with the same statement.
What is json file?
The tail() method returns the headers and a specified number of rows, starting from the
bottom.
Info About the Data
The DataFrames object has a method called info(), that gives you more information about
the data set.
Null Values
The info() method also tells us how many Non-Null values there are present in each column, and
in our data set it seems like there are 164 of 169 Non-Null values in the "Calories" column.
Which means that there are 5 rows with no value at all, in the "Calories" column, for whatever
reason.
Empty values, or Null values, can be bad when analyzing data, and you should consider
removing rows with empty values. This is a step towards what is called cleaning data, and you
will learn more about that in the next chapters.
Pandas - Cleaning Data
Another way of dealing with empty cells is to insert a new value instead.
This way you do not have to delete entire rows just because of some empty cells.
To only replace empty values for one column, specify the column name
for the DataFrame
Wrong Data
"Wrong data" does not have to be "empty cells" or "wrong format", it can just
be wrong, like if someone registered "199" instead of "1.99".
Sometimes you can spot wrong data by looking at the data set, because you
have an expectation of what it should be.
If you take a look at our data set, you can see that in row 7, the duration is 450,
but for all the other rows the duration is between 30 and 60.
It doesn't have to be wrong, but taking in consideration that this is the data set
of someone's workout sessions, we conclude with the fact that this person did
not work out in 450 minutes.
Replacing Values
One way to fix wrong values is to replace them with something else.
In our example, it is most likely a typo, and the value should be "45"
instead of "450", and we could just insert "45" in row 7:
Duplicate rows are rows that have been registered more than one time.
print(df.duplicated())
Removing Duplicates
To remove duplicates, use the drop_duplicates() method.
df.drop_duplicates(inplace = True)
Finding Relationships
A great aspect of the Pandas module is the corr() method.
The corr() method calculates the relationship between each column in your data set.
The corr() method ignores "not numeric" columns.
What is a good correlation? It depends on the use, but I think it is safe to say you have to
have at least 0.6 (or -0.6) to call it a good correlation.
Introduction to Data Visualization
Data visualization is the graphical representation of information and data. By using visual
elements like charts, graphs, and maps, data visualization tools provide an accessible way to
see and understand trends, outliers, and patterns in data.
Importance of Data Visualization
Simplifies Complex Data: Helps in simplifying complex data sets to make data-driven
decisions.
Identifies Trends and Patterns: Makes it easier to spot trends and patterns.
Communication: Effective for communicating data insights to stakeholders.
Comparisons: Makes comparisons between different data sets or variables more intuitive.
Decision Making: Aids in faster and more effective decision-making.
What is Matplotlib?
Matplotlib is a plotting library for the Python programming language and its numerical
mathematics extension, NumPy. It provides an object-oriented API for embedding plots
into applications using general-purpose GUI toolkits.
Why Use Matplotlib?
Matplotlib is one of the most widely used data visualization libraries in Python for several
reasons:
Versatility: It can create a wide range of static, animated, and interactive plots.
Customization: Highly customizable to suit various needs and preferences.
Integration: Integrates well with other Python libraries such as NumPy, Pandas, and
SciPy.
Output Formats: Supports various output formats like PNG, PDF, SVG, and more.
Community and Documentation: Well-documented with a large community, making it
easier to find support and examples.
Core Concepts of Matplotlib
Procedural programming
Functional programming
Object oriented programming
Concepts in oops
Class
Object
Polymorphism
Encapsulation
Inheritance
Abstraction
Constructor
Types of attributes
Class Attributes
Object attributes or instance attributes
Methods
Basically
Class is a combination of methods and attributes
Example
Attributes : in terms of car
so number of tyres,doors,seats,car body etc
Methods : how the car runs usings all this attributes
how the engine will start,how the brake will operate
etc
How to create method
#creating class
class Student:
def __init__(self,fullname) :
self.name=fullname
def hi(self): # creating a method according our requirment
print("hello",self.name)
# creating object
s1=Student("Arunpal")
s1.hi()
Abstraction
When one class (child/derived) derives the properties & methods of another another
class(parent/base).
Types
Single level
Multi_level inheritance
Multiple inheritance
Super()
Note – Static method can’t access or modify class state and generally
for utility.
class Student :
@classmethod
def collage(cls):
pass
Polymorphism
Data Validation:
Ensuring that user input meets specific criteria, such as email
addresses, phone numbers, passwords, etc.
Text Search and Extraction:
Searching for specific patterns within text and extracting
relevant information, such as URLs, dates, or mentions.
Data Cleaning and Transformation:
Cleaning up messy data by removing unwanted characters,
formatting inconsistencies, or extracting specific information.
Uses of regex