python 5
python 5
Errors:
Programming errors can be categorized into three types: Syntax errors, Runtime errors, and Logic
errors.
Syntax Errors
Error caused by not following the proper structure (syntax) of the language is called syntax
error or parsing error.
Example
>>>if a <3
File"<interactive input>", line 1
if a <3
^
SyntaxError: invalid syntax
In the example, the error is detected at if statement, since a colon (':') is missing at
the end of the statement.
Runtime Errors
Example
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
Logic Errors
Logic errors occur when a program does not perform the way it was intended to. Errors of
this kind occur for many different reasons.
Example: If user want to get the addition of 54 and 33 but instead of using
addition operator used minus operator.
>>>54 – 33
21
Exceptions
Whenever these types of runtime error occur, Python creates an exception object. If not
handled properly, it prints a traceback to that error along with some details about why that
error occurred.
Example
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 4 + spam*3
Python uses try and except keywords to handle exceptions. Both keywords are followed by
indented blocks.
Syntax:
try :
#statement in try block
except :
#executed when error in try block
The try: block contains one or more statements which are likely to encounter an exception. If the
statements in this block are executed without an exception, the subsequent except: block is
skipped.
If the exception does occur, the program flow is transferred to the except: block. The statements
in the except: block are meant to handle the cause of the exception appropriately.
try:
a=5
b='0'
print(a/b)
except:
print('Some error occurred.')
Output
Some error occurred.
Out of try except blocks.
A specific type of exception can be mentioned in front of except keyword. The subsequent block
will be executed only if the specified exception occurs.
Example:
try:
a=5
b='0'
print (a+b)
except TypeError:
print('Unsupported operation')
Output
Unsupported operation
Out of try except blocks
There may be multiple except clauses with different exception types in a single try block. If the
type of exception doesn't match any of except blocks, it will remain unhandled and the program
will terminate.
Example:
try:
a=5
b=0
print (a/b)
except TypeError:
print('Unsupported operation')
except ZeroDivisionError:
print ('Division by zero not allowed')
print ('Out of try except blocks')
Output
In Python, keywords else and finally can also be used along with the try and except clauses. While
except block is executed if the exception occurs inside the try block, the else block gets
processed if the try block is found to be exception free.
Syntax:
try :
#statement in try block
except :
#executed when error in try block
else :
#executed if try block is error-free
finally :
#executed irrespective of exception occurred or not
Example: Accepts two numbers from the user and performs their division.
try:
print("try block")
x = int(input('Enter a number: '))
y = int(input('Enter another number: '))
z = x/y
except ZeroDivisionError:
print("except ZeroDivisionError block")
print("Division by 0 not accepted")
else:
print("else block")
print("Division = ", z)
finally:
print("finally block")
x=0
y=0
print ("Out of try, except, else and finally blocks." )
Raise an Exception
Python also provides the raise keyword to be used in the context of exception handling. It causes
an exception to be generated explicitly. Built-in errors are raised implicitly. However, a built-in or
custom exception can be forced during execution.
try:
x = int(input('Enter a number upto 100: '))
if x > 100:
raise ValueError(x)
except ValueError:
print(x, "is out of allowed range")
else:
print(x, "is within the allowed range")
File Handling
The file handling plays an important role when the data needs to be stored permanently into the
file. A file is a named location on disk to store related information. We can access the stored
information (non-volatile) after the program termination.
In Python, files are treated in two modes as text or binary. The file may be in the text or binary
format, and each line of a file is ended with the special character.
o Open a file
o Read or write - Performing operation
o Close the file
Opening a file
Python provides an open( ) function that accepts two arguments, file name and access mode in
which the file is accessed. The function returns a file object which can be used to perform various
operations like reading, writing, etc.
Syntax:
f = open(filename, mode)
Here is a list of the different modes of opening a file −
Opens a file for reading only. The file pointer is placed at the beginning
1 r
of the file. This is the default mode.
Opens a file for reading only in binary format. The file pointer is placed
2 rb
at the beginning of the file. This is the default mode.
Opens a file for both reading and writing. The file pointer placed at the
3 r+
beginning of the file.
Opens a file for both reading and writing in binary format. The file
4 rb+
pointer placed at the beginning of the file.
Opens a file for writing only. Overwrites the file if the file exists. If the
5 w
file does not exist, creates a new file for writing.
Opens a file for writing only in binary format. Overwrites the file if the
6 wb
file exists. If the file does not exist, creates a new file for writing.
Opens a file for both writing and reading. Overwrites the existing file if
7 w+ the file exists. If the file does not exist, creates a new file for reading
and writing.
Opens a file for both writing and reading in binary format. Overwrites
8 wb+ the existing file if the file exists. If the file does not exist, creates a new
file for reading and writing.
Opens a file for appending. The file pointer is at the end of the file if the
9 a file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing.
Opens a file for appending in binary format. The file pointer is at the end
10 ab of the file if the file exists. That is, the file is in the append mode. If the
file does not exist, it creates a new file for writing.
Opens a file for both appending and reading. The file pointer is at the
11 a+ end of the file if the file exists. The file opens in the append mode. If the
file does not exist, it creates a new file for reading and writing.
Opens a file for both appending and reading in binary format. The file
pointer is at the end of the file if the file exists. The file opens in the
12 ab+
append mode. If the file does not exist, it creates a new file for reading
and writing.
Example:
f = open("sample.txt", "wb")
print ("Name of the file: ", f.name)
print ("Closed or not : ", f.closed)
print ("Opening mode : ", f.mode)
The Method
The close( ) method of a object flushes any unwritten information and closes the file object,
after which no more writing can be done.
Syntax:
fileObject.close( )
Example:
f = open("sample.txt", "wb")
print ("Name of the file: ", f.name)
f.close( )
The Method
The method writes any string to an open file. It is important to note that Python strings can
have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the string −
Syntax
fileObject.write(string)
Example:
f = open("sample.txt", "wb")
f.write( "Python is a great language.\n Its great!!\n")
f.close( )
The Method
f = open("sample.txt", "r+")
str = f.read(10);
print("Read String is : ", str)
f.close( )
Example 2:
f = open("sample.txt", "r+")
print("Read String is : ", f.read( ))
f.close( )
Python os module provides methods that help to perform file-processing operations, such as
renaming and deleting files.
The method assign new name to the existing file. It takes two arguments, the current
filename and the new filename.
Syntax
os.rename(current_file_name, new_file_name)
Example :
import os
os.rename(“ sample.txt” , “ sample1.txt” )
The Method
The method is used to delete files by supplying the name of the file to be deleted as the
argument.
Syntax
os.remove(file_name)
Example :
import os
os.remove(“ sample.txt” )
File Positions
Example:
f = open("sample.txt", "r+")
str = f.read(10)
print ("Read String is : ", str)
Python is known for its general-purpose nature that makes it applicable in almost every domain of
software development. Python makes its presence in every emerging field. It is the
fastest-growing programming language and can develop any application.
1) Web Applications
Python is used to develop web applications. It provides libraries to handle internet protocols such
as HTML and XML, JSON, Email processing, request, etc. One of Python web-framework named
Django is used on Instagram. Python provides many useful frameworks, and these are given
below:
The GUI stands for the Graphical User Interface, which provides a smooth interaction to any
application. Python provides a Tk GUI library to develop a user interface. Some popular GUI
libraries are given below.
o Tkinter or Tk
o wxWidgetM
o Kivy (used for writing multitouch applications )
3) Console-based Application
Console-based applications run from the command-line or shell. These applications are computer
program which are used commands to execute. Python can develop this kind of application very
effectively. It is famous for having REPL, which means the Read-Eval-Print Loop that makes it the
most suitable language for the command-line applications.
4) Software Development
Python is useful for the software development process. It works as a support language and can
be used to build control and management, testing, etc.
o Buildbot and Apache Gumps are used for automated continuous compilation and testing.
This is the era of Artificial intelligence where the machine can perform the task the same as the
human. Python language is the most suitable language for Artificial intelligence or machine
learning. It consists of many scientific and mathematical libraries, which makes easy to solve
complex calculations.
Few popular frameworks of machine libraries are given below.
o SciPy
o Scikit-learn
o NumPy
o Pandas
o Matplotlib
6) Business Applications
Business Applications differ from standard applications. E-commerce and ERP are an example of
a business application. This kind of application requires extensively, scalability and readability,
and Python provides all these features.
Oddo is an example of the all-in-one Python-based application which offers a range of business
applications.
Python is flexible to perform multiple tasks and can be used to create multimedia applications.
Some multimedia applications which are made by using Python are TimPlayer, cplay, etc. The
few multimedia libraries are given below.
o Gstreamer
o Pyglet
o QT Phonon
8) 3D CAD Applications
The CAD (Computer-aided design) is used to design engineering related architecture. It is used to
develop the 3D representation of a part of a system. Python can create a 3D CAD application by
using the following functionalities.
o Fandango (Popular )
o CAMVOX
o AnyCAD
o RCAM
Python contains many libraries that are used to work with the image. The image can be
manipulated according to our requirements. Some libraries of image processing are given below.
o OpenCV
o Pillow
o SimpleITK
SciPy:
SciPy in Python is an open-source library used for solving mathematical, scientific, engineering,
and technical problems. It allows users to manipulate the data and visualize the data using a wide
range of high-level Python commands. SciPy is built on the Python NumPy extention. SciPy is also
pronounced as “Sigh Pi.”
Use of SciPy
• SciPy contains varieties of sub packages which help to solve the most common issue
related to Scientific Computation.
• SciPy package in Python is the most used Scientific library only second to GNU Scientific
Library for C/C++ or Matlab’s.
• Easy to use and understand as well as fast computational power.
• It can operate on an array of NumPy library.
8. scipy.special SpecialFunction.
9. scipy.stats Statistics.
NetworkX
NetworkX is a Python package for the creation, manipulation, and study of the structure,
dynamics, and function of complex networks. It is used to study large complex networks
represented in form of graphs with nodes and edges.
Principal uses of NetworkX are:
• Study of the structure and dynamics of social, biological, and infrastructure networks
• Standardized programming environment for graphs
• Rapid development of collaborative, multidisciplinary projects
• Integration with algorithms and code written in C, C++, and FORTRAN
• Working with large nonstandard data sets
Installation
Importing
The command above will create an empty graph. An empty graph has an empty edge set
and an empty vertex set.
Creating Nodes
Creating Edges
Scikit-learn
Scikit-learn (Sklearn) is the most useful and robust library for machine learning in Python. It
provides a selection of efficient tools for machine learning and statistical modeling including
classification, regression, clustering and dimensionality reduction via a consistence interface in
Python. This library, which is largely written in Python, is built upon NumPy, SciPy and Matplotlib.
Features of scikit-learn:
• Simple and efficient tools for data mining and data analysis. It features various
classification, regression and clustering algorithms including support vector machines,
random forests, gradient boosting, k-means, etc.
• Accessible to everybody and reusable in various contexts.
• Built on the top of NumPy, SciPy, and matplotlib.
• Open source, commercially usable – BSD license.
• Clustering − This model is used for grouping unlabeled data.
• Cross Validation − It is used to check the accuracy of supervised models on unseen data.