SlideShare a Scribd company logo
What is an Array in Python?
An array is a collection of items stored at contiguous memory locations.
The idea is to store multiple items of the same type together.
This makes it easier to calculate the position of each element by simply
adding an offset to a base value, i.e., the memory location of the first
element of the array (generally denoted by the name of the array).
The array can be handled in Python by a module named array.
They can be useful when we have to manipulate only specific data type
values.
A user can treat lists as arrays.
However, the user cannot constrain the type of elements stored in a list.
If you create arrays using the array module, all elements of the array
must be of the same type.
Difference between Python Lists and Python Arrays?
List Array
Example:
my_list = [1, 2, 3, 4]
Example:
import array
arr = array.array(‘i’, [1, 2, 3])
No need to explicitly import a module for the declaration Need to explicitly import the array module for declaration
Cannot directly handle arithmetic operations Can directly handle arithmetic operations
Preferred for a shorter sequence of data items Preferred for a longer sequence of data items
Greater flexibility allows easy modification (addition,
deletion) of data
Less flexibility since addition, and deletion has to be done
element-wise
The entire list can be printed without any explicit looping A loop has to be formed to print or access the components of
the array
Consume larger memory for easy addition of elements Comparatively more compact in memory size
Nested lists can be of variable size Nested arrays has to be of same size.
How to Use Arrays in Python
In order to create Python arrays, you'll first have to import the array module which contains all
the necessary functions.
There are 3 ways you can import the array module:
1. By using import array at the top of the file. This includes the module array. You would then
go on to create an array using array.array().
import array
array.array()
2. Instead of having to type array.array() all the time, you could use import array as arr at the
top of the file, instead of import array alone. You would then create an array by typing arr.array().
The arr acts as an alias name, with the array constructor then immediately following it.
import array as arr
arr.array()
3. Lastly, you could also use from array import *, with * importing all the functionalities
available. You would then create an array by writing the array() constructor alone.
from array import *
array()
How to Define Arrays in Python
• Once you've imported the array module, you can then go on to define a Python array.
• The general syntax for creating an array looks like this:
variable_name = array(typecode,[elements])
Let's break it down:
• variable_name would be the name of the array.
• The typecode specifies what kind of elements would be stored in the array. Whether
it would be an array of integers, an array of floats or an array of any other Python
data type. Remember that all elements should be of the same data type.
• Inside square brackets you mention the elements that would be stored in the array,
with each element being separated by a comma.
• You can also create an empty array by just writing variable_name = array(typecode)
alone, without any elements.
Typecodes in Python
Below is a typecode table, with the different typecodes that can be
used with the different data types when defining Python arrays:
TYPECODE C TYPE PYTHON TYPE MEMORY SIZE
'b' signed char int 1
'B' unsigned char int 1
'u' wchar_t Unicode character 2
'h' signed short int 2
'H' unsigned short int 2
'i' signed int int 2
'I' unsigned int int 2
'l' signed long int 4
'L' unsigned long int 4
'q' signed long long int 8
'Q' unsigned long long int 8
'f' float float 4
'd' double float 8
Array Methods
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
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 first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Python has a set of built-in methods that you can use on lists/arrays.
import array as arr
numbers = arr.array('i',[10,20,30])
print("#access each individual element in an array and print it out on its
own.")
print(numbers)
print("#find out the exact number of elements ")
print(len(numbers))
print("#element's index number by using the index() method.")
print(numbers.index(10))
print("#one-by-one, with each loop iteration.")
for number in numbers:
print(number)
print("#use the range() function, and pass the len() method")
for value in range(len(numbers)):
print(numbers[value])
print("#use the slicing operator, which is a colon :")
print(numbers[:2])
print("#change the value of a specific element")
numbers[0] = 40
print(numbers)
print("#Add a New Value to an Array")
numbers.append(40)
print(numbers)
print("#Use the extend() method")
numbers.extend([40,50,60])
print(numbers)
print("#Use the insert() method, to add an item at a specific
position.")
numbers.insert(0,40)
print(numbers)
print("#You can also use the pop() method, and specify the
position of the element to be removed")
numbers.pop(0)
print(numbers)
define an array
• here is an example of how you would define an array in Python:
import array as arr
numbers = arr.array('i',[10,20,30])
print(numbers)
• #output
• #array('i', [10, 20, 30])
Examples
import array as arr
numbers = arr.array('i',[10.0,20,30])
print(numbers)
ERROR!Traceback (most recent call last): File "<string>", line 2, in <module>TypeError:
'float' object cannot be interpreted as an integer
import array as arr
numbers = arr.array('i',[10,20,30])
print(len(numbers))
O/P : 3
Access Individual Items in an Array in Python
• import array as arr
• numbers = arr.array('i',[10,20,30])
• print(numbers[0]) # gets the 1st element
• print(numbers[1]) # gets the 2nd element
• print(numbers[2]) # gets the 3rd element
• print(numbers[-1]) #gets last item
• print(numbers[-2]) #gets second to last item
• print(numbers[-3]) #gets first item
Search Through an Array in Python
import array as arr
numbers = arr.array('i',[10,20,30])
print(numbers.index(10))
Ex:2
import array as arr
numbers = arr.array('i',[10,20,30,10,20,30])
print(numbers.index(10))
O/p: Starting Index
NumPy Creating Arrays
NumPy is used to work with arrays. The array object in NumPy is called ndarray.
We can create a NumPy ndarray object by using the array() function.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))
Dimensions in Arrays
A dimension in arrays is one level of array depth (nested arrays).
• 0-D Arrays
0-D arrays, or Scalars, are the elements in an array.
Each value in an array is a 0-D array.
Example:
import numpy as np
arr = np.array(42)
print(arr)
O/p:42
• 1-D Arrays
An array that has 0-D arrays as its elements is called uni-dimensional or
1-D array.
These are the most common and basic arrays.
• Example: Create a 1-D array containing the values 1,2,3,4,5
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
O/P: [1 2 3 4 5]
• 2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.
These are often used to represent matrix or 2nd order tensors.
Note: NumPy has a whole sub module dedicated towards matrix operations called
numpy.mat
• Example: Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
O/P:
[[1 2 3]
[4 5 6]]
• 3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array.
These are often used to represent a 3rd order tensor.
• Example: Create a 3-D array with two 2-D arrays, both containing two arrays with the
values 1,2,3 and 4,5,6
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)
O/P:
[[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]]
Check Number of Dimensions?
NumPy Arrays provides the ndim attribute that returns an integer that tells us how many dimensions the array
have.
• Example: Check how many dimensions the arrays have:
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, "Dimension Array")
print(b.ndim, "Dimension Array")
print(c.ndim, "Dimension Array")
print(d.ndim, "Dimension Array")
O/P:
0 Dimension Array
1 Dimension Array
2 Dimension Array
3 Dimension Array
Higher Dimensional Arrays
An array can have any number of dimensions.
When the array is created, you can define the number of dimensions by using the ndmin
argument.
• Example: Create an array with 5 dimensions and verify that it has 5 dimensions
import numpy as np
arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr)
print('number of dimensions :', arr.ndim)
O/P:
[[[[[1 2 3 4]]]]]
number of dimensions : 5
In this array the innermost dimension (5th dim) has 4 elements, the 4th dim has 1
element that is the vector, the 3rd dim has 1 element that is the matrix with the vector,
the 2nd dim has 1 element that is 3D array and 1st dim has 1 element that is a 4D array.
Exception Handling
• Error in Python can be of two types i.e. Syntax errors and Exceptions.
• Errors are problems in a program due to which the program will stop
the execution.
• On the other hand, exceptions are raised when some internal events
occur which change the normal flow of the program.
1. The try block lets you test a block of code for errors.
2. The except block lets you handle the error.
3. The else block lets execute if try block not contain error
4. The finally block lets you execute code, regardless of the result of
the try- and except blocks
Difference between Syntax Error and Exceptions
Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It leads to the
termination of the program.
Example:
amount = 10000
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")
SyntaxError: expected ':‘
Exceptions: Exceptions are raised when the program is syntactically correct, but the code results in an
error.
This error does not stop the execution of the program, however, it changes the normal flow of the
program.
marks = 10000
a = marks / 0
print(a)
ZeroDivisionError: division by zero
Here in this code a is we are dividing the ‘marks’ by zero so a error will occur known as
‘ZeroDivisionError’
Different types of exceptions in python
In Python, there are several built-in Python exceptions that can be raised when an error occurs during the
execution of a program. Here are some of the most common types of exceptions in Python:
• SyntaxError: This exception is raised when the interpreter encounters a syntax error in the code, such as
a misspelled keyword, a missing colon, or an unbalanced parenthesis.
• TypeError: This exception is raised when an operation or function is applied to an object of the wrong
type, such as adding a string to an integer.
• NameError: This exception is raised when a variable or function name is not found in the current scope.
• IndexError: This exception is raised when an index is out of range for a list, tuple, or other sequence
types.
• KeyError: This exception is raised when a key is not found in a dictionary.
• ValueError: This exception is raised when a function or method is called with an invalid argument or
input, such as trying to convert a string to an integer when the string does not represent a valid integer.
• AttributeError: This exception is raised when an attribute or method is not found on an object, such as
trying to access a non-existent attribute of a class instance.
• IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails due to an
input/output error.
• ZeroDivisionError: This exception is raised when an attempt is made to divide a number by zero.
• ImportError: This exception is raised when an import statement fails to find or load a module.
Exception handling Blocks usage
Try:
write Risky code here
except:
print try block error message
else:
print if try block not contain any error
finally:
print always
Example 2:
try:
print(x)
except Exception as e:
print("An exception occurred",e)
Output: An exception occurred name 'x' is not defined
Example 1 :
try:
print(x)
except:
print("An exception occurred")
Output: An exception occurred
Handling Exceptions With the try and except Block
• In Python, you use the try and except block to catch and handle exceptions.
• Python executes code following the try statement as a normal part of the program.
• The code that follows the except statement is the program’s response to any exceptions in the preceding try clause:
Example 3:
a=10
b=5 #where a & b are normal Statements
try: #The exceptional statements are insert try block
print(a/b) #where a/b is a critical Statements
print("this is try block")
except Exception:
#if try block is not execute automatically Exception
block will execute followed by remaining statements
print("you can not perform a/b operation")
print("this is except block")
Example 4:
a=10
b=0 #where a & b are normal Statements
try: #The exceptional statements are insert try block
print(a/b) #where a/b is a critical Statements
print("this is try block")
except Exception:
#if try blockcis not execute automatically Exception
block will execute followed by remaining statements
print("you can not perform a/b operation")
print("this is except block")
Try, except, else blocks
Example 6:
#The try block does not raise any errors, so the
else block is executed:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Output:
Hello
Nothing went wrong
Example 5:
def fun(a):
if a < 4:
b = a/(a-3)
print("Value of b = ", b)
try:
fun(3)
Try:
fun(5)
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")
Output: ZeroDivisionError Occurred and Handled
Try,except,finally blocks
a=10
b=0
try:
print("resourse(like files ,databases) open")
print(a/b)
print("this is try block")
#print("resourse close")
except Exception:
print("you can not perform a/b operation")
print("this is except block")
#print("resourse close")
finally:
# finally block is used to close the resourses like files , databases in try block if you want to close instead of try and except block
we close the resourses in finally block
print("resourse close")
print("this is finally block")
print("stop")
Example 1:
a=10
b=0
try:
print("resourse open")
print(a/b)
print("this is try block")
except Exception as e:
print("you can not perform a/b operation",e) #where e is represents to know the which type of exception
print("this is except block")
finally:
print("resourse close")
print("stop")
O/p:
resourse open
you can not perform a/b operation division by zero
this is except block
resourse close
stop
• Example 2:
a=10
b=‘a’
try:
print("resourse open")
print(a/b)
print("this is try block")
except ZeroDivisionError as Z: #This block is only for ZeroDivisionError
print("you can not perform a/b operation",Z)
print("this is ZeroDivisionError block")
except TypeError as T: #This block is only for TypeError
print("you can not perform TypeError",T)
print("this is TypeError block")
except Exception as e: #for remaining all execptions this block is working
print("you can not perform a/b operation",e)
print("this is except block")
finally:
print("resourse close")
print("stop")
Output:
resourse open
you can not perform TypeError
unsupported operand type(s) for /: 'int'
and 'str'
this is TypeError block
resourse close
stop
Standard Libraries of Python
The Python Standard Library contains all of Python's syntax, semantics,
and tokens.
It has built-in modules that allow the user to access I/O and a few other
essential modules as well as fundamental functions.
The Python libraries have been written in the C language generally.
The Python standard library has more than 200 core modules. Because
of all of these factors, Python is a powerful programming language.
The Python Standard Library plays a crucial role.
Python's features can only be used by programmers who have it.
Python standard library
• TensorFlow: This library was developed by Google in collaboration with the
Brain Team. It is an open-source library used for high-level computations. It is
also used in machine learning and deep learning algorithms. It contains a large
number of tensor operations. Researchers also use this Python library to solve
complex computations in Mathematics and Physics.
• Matplotlib: This library is responsible for plotting numerical data. And that’s
why it is used in data analysis. It is also an open-source library and plots high-
defined figures like pie charts, histograms, scatterplots, graphs, etc.
• Pandas: Pandas are an important library for data scientists. It is an open-
source machine learning library that provides flexible high-level data
structures and a variety of analysis tools. It eases data analysis, data
manipulation, and cleaning of data. Pandas support operations like Sorting, Re-
indexing, Iteration, Concatenation, Conversion of data, Visualizations,
Aggregations, etc.
Python standard library
• Numpy: The name “Numpy” stands for “Numerical Python”. It is the commonly
used library. It is a popular machine learning library that supports large matrices
and multi-dimensional data. It consists of in-built mathematical functions for
easy computations. Even libraries like TensorFlow use Numpy internally to
perform several operations on tensors. Array Interface is one of the key features
of this library.
• SciPy: The name “SciPy” stands for “Scientific Python”. It is an open-source
library used for high-level scientific computations. This library is built over an
extension of Numpy. It works with Numpy to handle complex computations.
While Numpy allows sorting and indexing of array data, the numerical data code
is stored in SciPy. It is also widely used by application developers and engineers.
• Scrapy: It is an open-source library that is used for extracting data from websites.
It provides very fast web crawling and high-level screen scraping. It can also be
used for data mining and automated testing of data.
Python standard library
• Scikit-learn: It is a famous Python library to work with complex data.
Scikit-learn is an open-source library that supports machine learning. It
supports variously supervised and unsupervised algorithms like linear
regression, classification, clustering, etc. This library works in
association with Numpy and SciPy.
• PyGame: This library provides an easy interface to the Standard
Directmedia Library (SDL) platform-independent graphics, audio, and
input libraries. It is used for developing video games using computer
graphics and audio libraries along with Python programming language.
• PyTorch: PyTorch is the largest machine learning library that optimizes
tensor computations. It has rich APIs to perform tensor computations
with strong GPU acceleration. It also helps to solve application issues
related to neural networks.
Python standard library
• PyBrain: The name “PyBrain” stands for Python Based Reinforcement
Learning, Artificial Intelligence, and Neural Networks library. It is an open-
source library built for beginners in the field of Machine Learning. It provides
fast and easy-to-use algorithms for machine learning tasks. It is so flexible
and easily understandable and that’s why is really helpful for developers that
are new in research fields.
• Keras: Keras is a Python-based open-source neural network library that
enables in-depth research into deep neural networks. Keras emerges as a
viable option as deep learning becomes more common because, according
to its developers, it is an API (Application Programming Interface) designed
for humans rather than machines. Keras has a higher rate of adoption in the
research community and industry than TensorFlow or Theano.
• The TensorFlow backend engine should be downloaded first before Keras can
be installed.
PIP Installation
Checking if You Have PIP Installed on Windows
PIP is automatically installed with Python 3.4.x+.
However, depending on how Python was installed, PIP may not be available on the system
automatically.
Before installing PIP on Windows, check if it is already installed:
1. Launch the command prompt window by pressing Windows Key + X and clicking Run.
2. Type in cmd.exe and hit enter.
Alternatively, type cmd in the Windows search bar and click the "Command Prompt" icon.
3. Type the following command in the command prompt:
pip help
• PIP is a package management system that installs and manages software packages
written in Python.
• It stands for "Preferred Installer Program" or "Pip Installs Packages."
• The utility manages PyPI package installations from the command line.
Installing Python pip on Windows
• To ensure proper installation and use of pip we need to tick this
checklist to install pip python:
1. Download pip
2. Install pip
3. Verify Installation
4. Add pip to environment variables
Python pip Install and Download
Python PIP can be downloaded and installed with following methods:
5. Using cURL in Python
6. Manually install Python PIP on Windows
Method 1: Using Python cURL
• Curl is a UNIX command that is used to send the PUT, GET, and
POST requests to a URL. This tool is utilized for downloading files, testing
REST APIs, etc.
• It downloads the get-pip.py file.
• Follow these instructions to pip windows install:
• Step 1: Open the cmd terminal
• Step 2: In python, a curl is a tool for transferring data requests to and
from a server. Use the following command to request:
1. curl https://bootst/rap.pypa.io/get-pip.py -o
get-pip.py
2. python get-pip.py
Method 2: Manually install Python PIP on Windows
• Python pip must be manually installed on Windows. We can pip install
in Python by manually installing it. You might need to use the correct
version of the file from pypa.io if you’re using an earlier version of
Python or pip. Get the file and save it to a folder on your PC.
• Step 1: Download the get-pip.py (https://bootstrap.pypa.io/get-
pip.py) file and store it in the same directory as python is installed.
Step 2: Change the current path of the directory in the command line
to the path of the directory file exists.
Step 3: get-pip.py is a bootstrapping script that enables users to install
pip in Python environments. Here, we are installing pip python3. Run
the command given below:where the above
python get-pip.py
Step 4: Now wait through the installation process. Voila! pip is now
installed on your system.
Verification of the Installation Process
One can easily verify if the pip has been installed correctly by
performing a version check on the same. Just go to the command line
and execute the following command:
pip -V
or
pip --version
Adding PIP To Windows Environment Variables
If you are facing any path error then you can follow the following steps to add the
pip to your PATH. You can follow the following steps to adding pip to path windows
10 and set the Path:
• Go to System and Security > System in the Control Panel once it has been opened.
• On the left side, click the Advanced system settings link.
• Then select Environment Variables.
• Double-click the PATH variable under System Variables.
• Click New, and add the directory where pip is installed, e.g. C:Python33Scripts, and select
OK.
• Upgrading Pip On Windows
• pip can be upgraded using the following command.
python -m pip install -U pip
Downgrading PIP On Windows
python -m pip install pip==17.0

More Related Content

Similar to object oriented programing in python and pip (20)

Numpy in Python.docx
Numpy in Python.docxNumpy in Python.docx
Numpy in Python.docx
manohar25689
 
Python array
Python arrayPython array
Python array
Arnab Chakraborty
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
numpy.pdf
numpy.pdfnumpy.pdf
numpy.pdf
DrSudheerHanumanthak
 
NumPy.pptx
NumPy.pptxNumPy.pptx
NumPy.pptx
EN1036VivekSingh
 
Chapter 5-Numpy-Pandas.pptx python programming
Chapter 5-Numpy-Pandas.pptx python programmingChapter 5-Numpy-Pandas.pptx python programming
Chapter 5-Numpy-Pandas.pptx python programming
ssuser77162c
 
Numpy.pdf
Numpy.pdfNumpy.pdf
Numpy.pdf
Arvind Pathak
 
Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptx
MrMaster11
 
Week 11.pptx
Week 11.pptxWeek 11.pptx
Week 11.pptx
CruiseCH
 
arrays.pptx
arrays.pptxarrays.pptx
arrays.pptx
HarmanShergill5
 
Arrays
ArraysArrays
Arrays
Chukka Nikhil Chakravarthy
 
NumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptx
NumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptx
NumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptx
tahirnaquash2
 
Array assignment
Array assignmentArray assignment
Array assignment
Ahmad Kamal
 
Unit4pptx__2024_11_ 11_10_16_09.pptx
Unit4pptx__2024_11_      11_10_16_09.pptxUnit4pptx__2024_11_      11_10_16_09.pptx
Unit4pptx__2024_11_ 11_10_16_09.pptx
GImpact
 
NUMPY [Autosaved] .pptx
NUMPY [Autosaved]                    .pptxNUMPY [Autosaved]                    .pptx
NUMPY [Autosaved] .pptx
coolmanbalu123
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
NumPy.pptx
NumPy.pptxNumPy.pptx
NumPy.pptx
DrJasmineBeulahG
 
DS Unit 1.pptx
DS Unit 1.pptxDS Unit 1.pptx
DS Unit 1.pptx
chin463670
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
maznabili
 
CAP776Numpy.ppt
CAP776Numpy.pptCAP776Numpy.ppt
CAP776Numpy.ppt
kdr52121
 
Numpy in Python.docx
Numpy in Python.docxNumpy in Python.docx
Numpy in Python.docx
manohar25689
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
Chapter 5-Numpy-Pandas.pptx python programming
Chapter 5-Numpy-Pandas.pptx python programmingChapter 5-Numpy-Pandas.pptx python programming
Chapter 5-Numpy-Pandas.pptx python programming
ssuser77162c
 
Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptx
MrMaster11
 
Week 11.pptx
Week 11.pptxWeek 11.pptx
Week 11.pptx
CruiseCH
 
NumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptx
NumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptx
NumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptx
tahirnaquash2
 
Array assignment
Array assignmentArray assignment
Array assignment
Ahmad Kamal
 
Unit4pptx__2024_11_ 11_10_16_09.pptx
Unit4pptx__2024_11_      11_10_16_09.pptxUnit4pptx__2024_11_      11_10_16_09.pptx
Unit4pptx__2024_11_ 11_10_16_09.pptx
GImpact
 
NUMPY [Autosaved] .pptx
NUMPY [Autosaved]                    .pptxNUMPY [Autosaved]                    .pptx
NUMPY [Autosaved] .pptx
coolmanbalu123
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
DS Unit 1.pptx
DS Unit 1.pptxDS Unit 1.pptx
DS Unit 1.pptx
chin463670
 
CAP776Numpy.ppt
CAP776Numpy.pptCAP776Numpy.ppt
CAP776Numpy.ppt
kdr52121
 

Recently uploaded (20)

362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Pavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible PavementsPavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible Pavements
Sakthivel M
 
IntroSlides-June-GDG-Cloud-Munich community [email protected]
IntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdfIntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdf
IntroSlides-June-GDG-Cloud-Munich community [email protected]
Luiz Carneiro
 
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
Journal of Soft Computing in Civil Engineering
 
SEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair KitSEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair Kit
projectultramechanix
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
11th International Conference on Data Mining (DaMi 2025)
11th International Conference on Data Mining (DaMi 2025)11th International Conference on Data Mining (DaMi 2025)
11th International Conference on Data Mining (DaMi 2025)
kjim477n
 
Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)
pelumiadigun2006
 
May 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information TechnologyMay 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghjfHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
yadavshivank2006
 
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdfIrja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdfHow Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank
Guru Nanak Technical Institutions
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptxDevelopment of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Pavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible PavementsPavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible Pavements
Sakthivel M
 
SEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair KitSEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair Kit
projectultramechanix
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
11th International Conference on Data Mining (DaMi 2025)
11th International Conference on Data Mining (DaMi 2025)11th International Conference on Data Mining (DaMi 2025)
11th International Conference on Data Mining (DaMi 2025)
kjim477n
 
Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)
pelumiadigun2006
 
May 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information TechnologyMay 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghjfHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
yadavshivank2006
 
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdfIrja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdfHow Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptxDevelopment of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
Ad

object oriented programing in python and pip

  • 1. What is an Array in Python? An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). The array can be handled in Python by a module named array. They can be useful when we have to manipulate only specific data type values. A user can treat lists as arrays. However, the user cannot constrain the type of elements stored in a list. If you create arrays using the array module, all elements of the array must be of the same type.
  • 2. Difference between Python Lists and Python Arrays? List Array Example: my_list = [1, 2, 3, 4] Example: import array arr = array.array(‘i’, [1, 2, 3]) No need to explicitly import a module for the declaration Need to explicitly import the array module for declaration Cannot directly handle arithmetic operations Can directly handle arithmetic operations Preferred for a shorter sequence of data items Preferred for a longer sequence of data items Greater flexibility allows easy modification (addition, deletion) of data Less flexibility since addition, and deletion has to be done element-wise The entire list can be printed without any explicit looping A loop has to be formed to print or access the components of the array Consume larger memory for easy addition of elements Comparatively more compact in memory size Nested lists can be of variable size Nested arrays has to be of same size.
  • 3. How to Use Arrays in Python In order to create Python arrays, you'll first have to import the array module which contains all the necessary functions. There are 3 ways you can import the array module: 1. By using import array at the top of the file. This includes the module array. You would then go on to create an array using array.array(). import array array.array() 2. Instead of having to type array.array() all the time, you could use import array as arr at the top of the file, instead of import array alone. You would then create an array by typing arr.array(). The arr acts as an alias name, with the array constructor then immediately following it. import array as arr arr.array() 3. Lastly, you could also use from array import *, with * importing all the functionalities available. You would then create an array by writing the array() constructor alone. from array import * array()
  • 4. How to Define Arrays in Python • Once you've imported the array module, you can then go on to define a Python array. • The general syntax for creating an array looks like this: variable_name = array(typecode,[elements]) Let's break it down: • variable_name would be the name of the array. • The typecode specifies what kind of elements would be stored in the array. Whether it would be an array of integers, an array of floats or an array of any other Python data type. Remember that all elements should be of the same data type. • Inside square brackets you mention the elements that would be stored in the array, with each element being separated by a comma. • You can also create an empty array by just writing variable_name = array(typecode) alone, without any elements.
  • 5. Typecodes in Python Below is a typecode table, with the different typecodes that can be used with the different data types when defining Python arrays: TYPECODE C TYPE PYTHON TYPE MEMORY SIZE 'b' signed char int 1 'B' unsigned char int 1 'u' wchar_t Unicode character 2 'h' signed short int 2 'H' unsigned short int 2 'i' signed int int 2 'I' unsigned int int 2 'l' signed long int 4 'L' unsigned long int 4 'q' signed long long int 8 'Q' unsigned long long int 8 'f' float float 4 'd' double float 8
  • 6. Array Methods 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 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 first item with the specified value reverse() Reverses the order of the list sort() Sorts the list Python has a set of built-in methods that you can use on lists/arrays.
  • 7. import array as arr numbers = arr.array('i',[10,20,30]) print("#access each individual element in an array and print it out on its own.") print(numbers) print("#find out the exact number of elements ") print(len(numbers)) print("#element's index number by using the index() method.") print(numbers.index(10)) print("#one-by-one, with each loop iteration.") for number in numbers: print(number) print("#use the range() function, and pass the len() method") for value in range(len(numbers)): print(numbers[value]) print("#use the slicing operator, which is a colon :") print(numbers[:2]) print("#change the value of a specific element") numbers[0] = 40 print(numbers) print("#Add a New Value to an Array") numbers.append(40) print(numbers) print("#Use the extend() method") numbers.extend([40,50,60]) print(numbers) print("#Use the insert() method, to add an item at a specific position.") numbers.insert(0,40) print(numbers) print("#You can also use the pop() method, and specify the position of the element to be removed") numbers.pop(0) print(numbers)
  • 8. define an array • here is an example of how you would define an array in Python: import array as arr numbers = arr.array('i',[10,20,30]) print(numbers) • #output • #array('i', [10, 20, 30])
  • 9. Examples import array as arr numbers = arr.array('i',[10.0,20,30]) print(numbers) ERROR!Traceback (most recent call last): File "<string>", line 2, in <module>TypeError: 'float' object cannot be interpreted as an integer import array as arr numbers = arr.array('i',[10,20,30]) print(len(numbers)) O/P : 3
  • 10. Access Individual Items in an Array in Python • import array as arr • numbers = arr.array('i',[10,20,30]) • print(numbers[0]) # gets the 1st element • print(numbers[1]) # gets the 2nd element • print(numbers[2]) # gets the 3rd element • print(numbers[-1]) #gets last item • print(numbers[-2]) #gets second to last item • print(numbers[-3]) #gets first item
  • 11. Search Through an Array in Python import array as arr numbers = arr.array('i',[10,20,30]) print(numbers.index(10)) Ex:2 import array as arr numbers = arr.array('i',[10,20,30,10,20,30]) print(numbers.index(10)) O/p: Starting Index
  • 12. NumPy Creating Arrays NumPy is used to work with arrays. The array object in NumPy is called ndarray. We can create a NumPy ndarray object by using the array() function. import numpy as np arr = np.array([1, 2, 3, 4, 5]) print(arr) print(type(arr))
  • 13. Dimensions in Arrays A dimension in arrays is one level of array depth (nested arrays). • 0-D Arrays 0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array. Example: import numpy as np arr = np.array(42) print(arr) O/p:42
  • 14. • 1-D Arrays An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array. These are the most common and basic arrays. • Example: Create a 1-D array containing the values 1,2,3,4,5 import numpy as np arr = np.array([1, 2, 3, 4, 5]) print(arr) O/P: [1 2 3 4 5]
  • 15. • 2-D Arrays An array that has 1-D arrays as its elements is called a 2-D array. These are often used to represent matrix or 2nd order tensors. Note: NumPy has a whole sub module dedicated towards matrix operations called numpy.mat • Example: Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6 import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6]]) print(arr) O/P: [[1 2 3] [4 5 6]]
  • 16. • 3-D arrays An array that has 2-D arrays (matrices) as its elements is called 3-D array. These are often used to represent a 3rd order tensor. • Example: Create a 3-D array with two 2-D arrays, both containing two arrays with the values 1,2,3 and 4,5,6 import numpy as np arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]]) print(arr) O/P: [[[1 2 3] [4 5 6]] [[1 2 3] [4 5 6]]]
  • 17. Check Number of Dimensions? NumPy Arrays provides the ndim attribute that returns an integer that tells us how many dimensions the array have. • Example: Check how many dimensions the arrays have: 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, "Dimension Array") print(b.ndim, "Dimension Array") print(c.ndim, "Dimension Array") print(d.ndim, "Dimension Array") O/P: 0 Dimension Array 1 Dimension Array 2 Dimension Array 3 Dimension Array
  • 18. Higher Dimensional Arrays An array can have any number of dimensions. When the array is created, you can define the number of dimensions by using the ndmin argument. • Example: Create an array with 5 dimensions and verify that it has 5 dimensions import numpy as np arr = np.array([1, 2, 3, 4], ndmin=5) print(arr) print('number of dimensions :', arr.ndim) O/P: [[[[[1 2 3 4]]]]] number of dimensions : 5 In this array the innermost dimension (5th dim) has 4 elements, the 4th dim has 1 element that is the vector, the 3rd dim has 1 element that is the matrix with the vector, the 2nd dim has 1 element that is 3D array and 1st dim has 1 element that is a 4D array.
  • 19. Exception Handling • Error in Python can be of two types i.e. Syntax errors and Exceptions. • Errors are problems in a program due to which the program will stop the execution. • On the other hand, exceptions are raised when some internal events occur which change the normal flow of the program. 1. The try block lets you test a block of code for errors. 2. The except block lets you handle the error. 3. The else block lets execute if try block not contain error 4. The finally block lets you execute code, regardless of the result of the try- and except blocks
  • 20. Difference between Syntax Error and Exceptions Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It leads to the termination of the program. Example: amount = 10000 if(amount > 2999) print("You are eligible to purchase Dsa Self Paced") SyntaxError: expected ':‘ Exceptions: Exceptions are raised when the program is syntactically correct, but the code results in an error. This error does not stop the execution of the program, however, it changes the normal flow of the program. marks = 10000 a = marks / 0 print(a) ZeroDivisionError: division by zero Here in this code a is we are dividing the ‘marks’ by zero so a error will occur known as ‘ZeroDivisionError’
  • 21. Different types of exceptions in python In Python, there are several built-in Python exceptions that can be raised when an error occurs during the execution of a program. Here are some of the most common types of exceptions in Python: • SyntaxError: This exception is raised when the interpreter encounters a syntax error in the code, such as a misspelled keyword, a missing colon, or an unbalanced parenthesis. • TypeError: This exception is raised when an operation or function is applied to an object of the wrong type, such as adding a string to an integer. • NameError: This exception is raised when a variable or function name is not found in the current scope. • IndexError: This exception is raised when an index is out of range for a list, tuple, or other sequence types. • KeyError: This exception is raised when a key is not found in a dictionary. • ValueError: This exception is raised when a function or method is called with an invalid argument or input, such as trying to convert a string to an integer when the string does not represent a valid integer. • AttributeError: This exception is raised when an attribute or method is not found on an object, such as trying to access a non-existent attribute of a class instance. • IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails due to an input/output error. • ZeroDivisionError: This exception is raised when an attempt is made to divide a number by zero. • ImportError: This exception is raised when an import statement fails to find or load a module.
  • 22. Exception handling Blocks usage Try: write Risky code here except: print try block error message else: print if try block not contain any error finally: print always Example 2: try: print(x) except Exception as e: print("An exception occurred",e) Output: An exception occurred name 'x' is not defined Example 1 : try: print(x) except: print("An exception occurred") Output: An exception occurred
  • 23. Handling Exceptions With the try and except Block • In Python, you use the try and except block to catch and handle exceptions. • Python executes code following the try statement as a normal part of the program. • The code that follows the except statement is the program’s response to any exceptions in the preceding try clause: Example 3: a=10 b=5 #where a & b are normal Statements try: #The exceptional statements are insert try block print(a/b) #where a/b is a critical Statements print("this is try block") except Exception: #if try block is not execute automatically Exception block will execute followed by remaining statements print("you can not perform a/b operation") print("this is except block") Example 4: a=10 b=0 #where a & b are normal Statements try: #The exceptional statements are insert try block print(a/b) #where a/b is a critical Statements print("this is try block") except Exception: #if try blockcis not execute automatically Exception block will execute followed by remaining statements print("you can not perform a/b operation") print("this is except block")
  • 24. Try, except, else blocks Example 6: #The try block does not raise any errors, so the else block is executed: try: print("Hello") except: print("Something went wrong") else: print("Nothing went wrong") Output: Hello Nothing went wrong Example 5: def fun(a): if a < 4: b = a/(a-3) print("Value of b = ", b) try: fun(3) Try: fun(5) except ZeroDivisionError: print("ZeroDivisionError Occurred and Handled") except NameError: print("NameError Occurred and Handled") Output: ZeroDivisionError Occurred and Handled
  • 25. Try,except,finally blocks a=10 b=0 try: print("resourse(like files ,databases) open") print(a/b) print("this is try block") #print("resourse close") except Exception: print("you can not perform a/b operation") print("this is except block") #print("resourse close") finally: # finally block is used to close the resourses like files , databases in try block if you want to close instead of try and except block we close the resourses in finally block print("resourse close") print("this is finally block") print("stop")
  • 26. Example 1: a=10 b=0 try: print("resourse open") print(a/b) print("this is try block") except Exception as e: print("you can not perform a/b operation",e) #where e is represents to know the which type of exception print("this is except block") finally: print("resourse close") print("stop") O/p: resourse open you can not perform a/b operation division by zero this is except block resourse close stop
  • 27. • Example 2: a=10 b=‘a’ try: print("resourse open") print(a/b) print("this is try block") except ZeroDivisionError as Z: #This block is only for ZeroDivisionError print("you can not perform a/b operation",Z) print("this is ZeroDivisionError block") except TypeError as T: #This block is only for TypeError print("you can not perform TypeError",T) print("this is TypeError block") except Exception as e: #for remaining all execptions this block is working print("you can not perform a/b operation",e) print("this is except block") finally: print("resourse close") print("stop") Output: resourse open you can not perform TypeError unsupported operand type(s) for /: 'int' and 'str' this is TypeError block resourse close stop
  • 28. Standard Libraries of Python The Python Standard Library contains all of Python's syntax, semantics, and tokens. It has built-in modules that allow the user to access I/O and a few other essential modules as well as fundamental functions. The Python libraries have been written in the C language generally. The Python standard library has more than 200 core modules. Because of all of these factors, Python is a powerful programming language. The Python Standard Library plays a crucial role. Python's features can only be used by programmers who have it.
  • 29. Python standard library • TensorFlow: This library was developed by Google in collaboration with the Brain Team. It is an open-source library used for high-level computations. It is also used in machine learning and deep learning algorithms. It contains a large number of tensor operations. Researchers also use this Python library to solve complex computations in Mathematics and Physics. • Matplotlib: This library is responsible for plotting numerical data. And that’s why it is used in data analysis. It is also an open-source library and plots high- defined figures like pie charts, histograms, scatterplots, graphs, etc. • Pandas: Pandas are an important library for data scientists. It is an open- source machine learning library that provides flexible high-level data structures and a variety of analysis tools. It eases data analysis, data manipulation, and cleaning of data. Pandas support operations like Sorting, Re- indexing, Iteration, Concatenation, Conversion of data, Visualizations, Aggregations, etc.
  • 30. Python standard library • Numpy: The name “Numpy” stands for “Numerical Python”. It is the commonly used library. It is a popular machine learning library that supports large matrices and multi-dimensional data. It consists of in-built mathematical functions for easy computations. Even libraries like TensorFlow use Numpy internally to perform several operations on tensors. Array Interface is one of the key features of this library. • SciPy: The name “SciPy” stands for “Scientific Python”. It is an open-source library used for high-level scientific computations. This library is built over an extension of Numpy. It works with Numpy to handle complex computations. While Numpy allows sorting and indexing of array data, the numerical data code is stored in SciPy. It is also widely used by application developers and engineers. • Scrapy: It is an open-source library that is used for extracting data from websites. It provides very fast web crawling and high-level screen scraping. It can also be used for data mining and automated testing of data.
  • 31. Python standard library • Scikit-learn: It is a famous Python library to work with complex data. Scikit-learn is an open-source library that supports machine learning. It supports variously supervised and unsupervised algorithms like linear regression, classification, clustering, etc. This library works in association with Numpy and SciPy. • PyGame: This library provides an easy interface to the Standard Directmedia Library (SDL) platform-independent graphics, audio, and input libraries. It is used for developing video games using computer graphics and audio libraries along with Python programming language. • PyTorch: PyTorch is the largest machine learning library that optimizes tensor computations. It has rich APIs to perform tensor computations with strong GPU acceleration. It also helps to solve application issues related to neural networks.
  • 32. Python standard library • PyBrain: The name “PyBrain” stands for Python Based Reinforcement Learning, Artificial Intelligence, and Neural Networks library. It is an open- source library built for beginners in the field of Machine Learning. It provides fast and easy-to-use algorithms for machine learning tasks. It is so flexible and easily understandable and that’s why is really helpful for developers that are new in research fields. • Keras: Keras is a Python-based open-source neural network library that enables in-depth research into deep neural networks. Keras emerges as a viable option as deep learning becomes more common because, according to its developers, it is an API (Application Programming Interface) designed for humans rather than machines. Keras has a higher rate of adoption in the research community and industry than TensorFlow or Theano. • The TensorFlow backend engine should be downloaded first before Keras can be installed.
  • 33. PIP Installation Checking if You Have PIP Installed on Windows PIP is automatically installed with Python 3.4.x+. However, depending on how Python was installed, PIP may not be available on the system automatically. Before installing PIP on Windows, check if it is already installed: 1. Launch the command prompt window by pressing Windows Key + X and clicking Run. 2. Type in cmd.exe and hit enter. Alternatively, type cmd in the Windows search bar and click the "Command Prompt" icon. 3. Type the following command in the command prompt: pip help • PIP is a package management system that installs and manages software packages written in Python. • It stands for "Preferred Installer Program" or "Pip Installs Packages." • The utility manages PyPI package installations from the command line.
  • 34. Installing Python pip on Windows • To ensure proper installation and use of pip we need to tick this checklist to install pip python: 1. Download pip 2. Install pip 3. Verify Installation 4. Add pip to environment variables Python pip Install and Download Python PIP can be downloaded and installed with following methods: 5. Using cURL in Python 6. Manually install Python PIP on Windows
  • 35. Method 1: Using Python cURL • Curl is a UNIX command that is used to send the PUT, GET, and POST requests to a URL. This tool is utilized for downloading files, testing REST APIs, etc. • It downloads the get-pip.py file. • Follow these instructions to pip windows install: • Step 1: Open the cmd terminal • Step 2: In python, a curl is a tool for transferring data requests to and from a server. Use the following command to request: 1. curl https://bootst/rap.pypa.io/get-pip.py -o get-pip.py 2. python get-pip.py
  • 36. Method 2: Manually install Python PIP on Windows • Python pip must be manually installed on Windows. We can pip install in Python by manually installing it. You might need to use the correct version of the file from pypa.io if you’re using an earlier version of Python or pip. Get the file and save it to a folder on your PC. • Step 1: Download the get-pip.py (https://bootstrap.pypa.io/get- pip.py) file and store it in the same directory as python is installed.
  • 37. Step 2: Change the current path of the directory in the command line to the path of the directory file exists. Step 3: get-pip.py is a bootstrapping script that enables users to install pip in Python environments. Here, we are installing pip python3. Run the command given below:where the above python get-pip.py Step 4: Now wait through the installation process. Voila! pip is now installed on your system.
  • 38. Verification of the Installation Process One can easily verify if the pip has been installed correctly by performing a version check on the same. Just go to the command line and execute the following command: pip -V or pip --version
  • 39. Adding PIP To Windows Environment Variables If you are facing any path error then you can follow the following steps to add the pip to your PATH. You can follow the following steps to adding pip to path windows 10 and set the Path: • Go to System and Security > System in the Control Panel once it has been opened. • On the left side, click the Advanced system settings link. • Then select Environment Variables. • Double-click the PATH variable under System Variables. • Click New, and add the directory where pip is installed, e.g. C:Python33Scripts, and select OK. • Upgrading Pip On Windows • pip can be upgraded using the following command. python -m pip install -U pip Downgrading PIP On Windows python -m pip install pip==17.0