Unit-2 Python

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

Unit-2

Exception Handling
Errors: 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.

Errors are the 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 changes the
normal flow of the program.
Two types of Error occurs in python.

1. Syntax errors
2. Logical errors (Exceptions)

Syntax errors
When the proper syntax of the language is not followed then a syntax error is thrown.
Example

 Python3

# initialize the amount variable

amount = 10000

# check that You are eligible to

# purchase Dsa Self Paced or not

if(amount>2999)

print("You are eligible to purchase Dsa Self Paced")

Output:
It returns a syntax error message because after the if statement a colon: is missing. We can
fix this by writing the correct syntax.

logical errors(Exception)
When in the runtime an error that occurs after passing the syntax test is called exception or
logical type. For example, when we divide any number by zero then the ZeroDivisionError
exception is raised, or when we import a module that does not exist then ImportError is
raised.
Example 1:

 Python3

# initialize the amount variable

marks = 10000

# perform division with 0

a = marks / 0

print(a)

Output:

In the above example the ZeroDivisionError as we are trying to divide a number by 0.


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.
Example:
 Python3

# initialize the amount variable

marks = 10000

# perform division with 0

a = marks / 0

print(a)

Output:

In the above example raised the ZeroDivisionError as we are trying to divide a


number by 0.

Error Handling
When an error and an exception are raised then we handle that with the help of the
Handling method.

 Handling Exceptions with Try/Except/Finally


We can handle errors by the Try/Except/Finally method. we write unsafe code in
the try, fall back code in except and final code in finally block.
Example
 Python3

# put unsafe operation in try block

try:

print("code start")

# unsafe operation perform

print(1 / 0)

# if error occur the it goes in except block

except:

print("an error occurs")

# final code in finally block

finally:

print("GeeksForGeeks")

 Output:

code start
an error occurs
GeeksForGeeks

 Raising exceptions for a predefined condition
When we want to code for the limitation of certain conditions then we can raise
an exception.
Example
 Python3

# try for unsafe code

try:

amount = 1999

if amount < 2999:

# raise the ValueError

raise ValueError("please add money in your account")

else:

print("You are eligible to purchase DSA Self Paced course")

# if false then raise the value error

except ValueError as e:

print(e)

 Output:

please add money in your account

File Handling in Python


File handling in Python is a powerful and versatile tool that can be used to perform a
wide range of operations. However, it is important to carefully consider the
advantages and disadvantages of file handling when writing Python programs, to
ensure that the code is secure, reliable, and performs well.
Python File Handling
Python too supports file handling and allows users to handle files i.e., to read and
write files, along with many other file handling options, to operate on files. The
concept of file handling has stretched over various other languages, but the
implementation is either complicated or lengthy, but like other concepts of Python,
this concept here is also easy and short. Python treats files differently as text or binary
and this is important. Each line of code includes a sequence of characters and they
form a text file. Each line of a file is terminated with a special character, called the
EOL or End of Line characters like comma {,} or newline character. It ends the
current line and tells the interpreter a new one has begun. Let’s start with the reading
and writing files.
Advantages of File Handling
 Versatility: File handling in Python allows you to perform a wide range of
operations, such as creating, reading, writing, appending, renaming, and deleting
files.
 Flexibility: File handling in Python is highly flexible, as it allows you to work
with different file types (e.g. text files, binary files, CSV files, etc.), and to perform
different operations on files (e.g. read, write, append, etc.).
 User–friendly: Python provides a user-friendly interface for file handling, making
it easy to create, read, and manipulate files.
 Cross-platform: Python file-handling functions work across different platforms
(e.g. Windows, Mac, Linux), allowing for seamless integration and compatibility.
Disadvantages of File Handling
 Error-prone: File handling operations in Python can be prone to errors, especially
if the code is not carefully written or if there are issues with the file system (e.g.
file permissions, file locks, etc.).
 Security risks: File handling in Python can also pose security risks, especially if
the program accepts user input that can be used to access or modify sensitive files
on the system.
 Complexity: File handling in Python can be complex, especially when working
with more advanced file formats or operations. Careful attention must be paid to
the code to ensure that files are handled properly and securely.
 Performance: File handling operations in Python can be slower than other
programming languages, especially when dealing with large files or performing
complex operations.
For this article, we will consider the following “geeks.txt” file as an example.
Hello world
GeeksforGeeks
123 456
Working of open() Function in Python
Before performing any operation on the file like reading or writing, first, we have to
open that file. For this, we should use Python’s inbuilt function open() but at the time
of opening, we have to specify the mode, which represents the purpose of the opening
file.
f = open(filename, mode)
Where the following mode is supported:
1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already contains some data
then it will be overridden but if the file is not present then it creates the file as well.
3. a: open an existing file for append operation. It won’t override existing data.
4. r+: To read and write data into the file. The previous data in the file will be
overridden.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won’t override existing data.
Working in Read mode
There is more than one way to read a file in Python. Let us see how we can read the
content of a file in read mode.
Example 1: The open command will open the file in the read mode and the for loop
will print each line present in the file.
 Python3

# a file named "geek", will be opened with the reading mode.

file = open('geek.txt', 'r')

# This will print every line one by one in the file

for each in file:

print (each)

Output:
Hello world

GeeksforGeeks

123 456
Example 2: In this example, we will extract a string that contains all characters in the
file then we can use file.read().
 Python3

# Python code to illustrate read() mode

file = open("geeks.txt", "r")


print (file.read())

Output:
Hello world
GeeksforGeeks
123 456
Example 3: In this example, we will see how we can read a file using
the with statement.
 Python3

# Python code to illustrate with()

with open("geeks.txt") as file:

data = file.read()

print(data)

Output:
Hello world
GeeksforGeeks
123 456
Example 4: Another way to read a file is to call a certain number of characters like in
the following code the interpreter will read the first five characters of stored data and
return it as a string:
 Python3

# Python code to illustrate read() mode character wise

file = open("geeks.txt", "r")

print (file.read(5))

Output:
Hello
Creating a File using the write() Function
Just like reading a file in Python, there are a number of ways to write in a file in
Python. Let us see how we can write the content of a file using the write() function in
Python.
Working in Write Mode
Let’s see how to create a file and how the write mode works.
Example 1: In this example, we will see how the write mode and the write() function
is used to write in a file. The close() command terminates all the resources in use and
frees the system of this particular program.
 Python3

# Python code to create a file

file = open('geek.txt','w')

file.write("This is the write command")

file.write("It allows us to write in a particular file")

file.close()

Output:
This is the write commandIt allows us to write in a particular file
Example 2: We can also use the written statement along with the with() function.
 Python3

# Python code to illustrate with() alongwith write()

with open("file.txt", "w") as f:

f.write("Hello World!!!")

Output:
Hello World!!!
Working of Append Mode
Let us see how the append mode works.
Example: For this example, we will use the file created in the previous example.
 Python3
# Python code to illustrate append() mode

file = open('geek.txt', 'a')

file.write("This will add this line")

file.close()

Output:
This is the write commandIt allows us to write in a particular fileThis will add this line

Python Classes/Objects

Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class

To create a class, use the keyword class:

Prog:

class MyClass:

x=5

print(x)

print("Class is a blueprint")

Output:
5

Class is a blueprint

Create Object

Now we can use the class named MyClass to create objects:

Example: Create an object named p1, and print the value of x:


Prog:

class MyClass:

x=5

p1 = MyClass()

print(p1.x)

Output:

The __init__() Function


The examples above are classes and objects in their simplest form, and are not really useful in
real life applications.

To understand the meaning of classes we have to understand the built-in __init__() function.

All classes have a function called __init__(), which is always executed when the class is being
initiated.

Use the __init__() function to assign values to object properties, or other operations that are
necessary to do when the object is being created:

Example
Create a class named Person, use the __init__() function to assign values for name and age:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)
print(p1.name)
print(p1.age)

Output:

John

36

Note: The __init__() function is called automatically every time the class is being used to create
a new object.

Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the object.

Let us create a method in the Person class:

Example
Insert a function that prints a greeting, and execute it on the p1 object:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()

Output:Hello my name is John

Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code
reusability to the program because we can use an existing class to create a new class instead
of creating it from scratch.

In inheritance, the child class acquires the properties and can access all the data members and
functions defined in the parent class. A child class can also provide its specific
implementation to the functions of the parent class. In this section of the tutorial, we will
discuss inheritance in detail.

In python, a derived class can inherit base class by just mentioning the base in the bracket
after the derived class name. Consider the following syntax to inherit a base class into the
derived class.

Syntax
1. class derived-class(base class):
2. <class-suite>

A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the
following syntax.

Syntax
1. class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
2. <class - suite>

Example 1
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. d = Dog()
9. d.bark()
10. d.speak()
Output:

dog barking
Animal Speaking

Python Multi-Level inheritance


Multi-Level inheritance is possible in python like other object-oriented languages. Multi-
level inheritance is archived when a derived class inherits another derived class. There is no
limit on the number of levels up to which, the multi-level inheritance is archived in python.

The syntax of multi-level inheritance is given below.

Syntax
1. class class1:
2. <class-suite>
3. class class2(class1):
4. <class suite>
5. class class3(class2):
6. <class suite>
7. .
8. .
Example
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #The child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. #The child class Dogchild inherits another child class Dog
9. class DogChild(Dog):
10. def eat(self):
11. print("Eating bread...")
12. d = DogChild()
13. d.bark()
14. d.speak()
15. d.eat()

Output:

dog barking
Animal Speaking
Eating bread...

Python Multiple inheritance


Python provides us the flexibility to inherit multiple base classes in the child class.

The syntax to perform multiple inheritance is given below.


Syntax
1. class Base1:
2. <class-suite>
3.
4. class Base2:
5. <class-suite>
6. .
7. .
8. .
9. class BaseN:
10. <class-suite>
11.
12. class Derived(Base1, Base2, ...... BaseN):
13. <class-suite>

Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(d.Summation(10,20))
12. print(d.Multiplication(10,20))
13. print(d.Divide(10,20))

Output:

30
200
0.5
Polymorphism in Python
What is polymorphism? Polymorphism refers to having multiple forms. Polymorphism is a
programming term that refers to the use of the same function name, but with different
signatures, for multiple types.

Example of in-built polymorphic functions:

1. # Python program for demonstrating the in-built poly-morphic functions


2.
3. # len() function is used for a string
4. print (len("Javatpoint"))
5.
6. # len() function is used for a list
7. print (len([110, 210, 130, 321]))

Output:

10
4

Iterator
An iterator is an object which contains a countable number of values and it is used to
iterate over iterable objects like list, tuples, sets, etc. Iterators are implemented using
a class and a local variable for iterating is not required here, It follows lazy
evaluation where the evaluation of the expression will be on hold and stored in the
memory until the item is called specifically which helps us to avoid repeated
evaluation. As lazy evaluation is implemented, it requires only 1 memory location to
process the value and when we are using a large dataset then, wastage of RAM space
will be reduced the need to load the entire dataset at the same time will not be there.
Using an iterator-
 iter() keyword is used to create an iterator containing an iterable object.
 next() keyword is used to call the next element in the iterable object.
 After the iterable object is completed, to use them again reassign them to the
same object.
Example:
 Python3

iter_list = iter(['Geeks', 'For', 'Geeks'])


print(next(iter_list))

print(next(iter_list))

print(next(iter_list))

Output:
Geeks
For
Geeks
Generators
It is another way of creating iterators in a simple way where it uses the keyword
“yield” instead of returning it in a defined function. Generators are implemented
using a function. Just as iterators, generators also follow lazy evaluation. Here, the
yield function returns the data without affecting or exiting the function. It will return
a sequence of data in an iterable format where we need to iterate over the sequence
to use the data as they won’t store the entire sequence in the memory.
Example:
 Python3

def sq_numbers(n):

for i in range(1, n+1):

yield i*i

a = sq_numbers(3)

print("The square of numbers 1,2,3 are : ")


print(next(a))

print(next(a))

print(next(a))

Output:
The square of numbers 1,2,3 are :
1
4
9

Table of difference between Iterator vs Generators


Iterator Generator

Function is used to
Class is used to implement an iterator
implement a generator.

All the local variables


Local Variables aren’t used here. before the yield function
are stored.

Generators are mostly used


in loops to generate an
Iterators are used mostly to iterate or convert other objects iterator by returning all the
to an iterator using iter() function. values in the loop without
affecting the iteration of
the loop

Generator uses yield


Iterator uses iter() and next() functions
keyword

Every generator is an
Every iterator is not a generator
iterator
Any and All are two built-in functions provided in python used for successive
And/Or. Any Returns true if any of the items is True. It returns False if empty or all
are false. Any can be thought of as a sequence of OR operations on the provided
iterables. It short circuit the execution i.e. stop the execution as soon as the result is
known.
Syntax:
any(list of iterables)

 Python

# Since all are false, false is returned

print (any([False, False, False, False]))

# Here the method will short-circuit at the

# second item (True) and will return True.

print (any([False, True, False, False]))

# Here the method will short-circuit at the

# first (True) and will return True.

print (any([True, False, False, False]))

Output:
False
True
True
All Returns true if all of the items are True (or if the iterable is empty). All can be
thought of as a sequence of AND operations on the provided iterables. It also short
circuit the execution i.e. stop the execution as soon as the result is known.

Syntax :
all(list of iterables)
 Python

# Here all the iterables are True so all

# will return True and the same will be printed

print (all([True, True, True, True]))

# Here the method will short-circuit at the

# first item (False) and will return False.

print (all([False, True, True, False]))

# This statement will return False, as no

# True is found in the iterables

print (all([False, False, False]))

Output :
True
False
False

What is data compression?


Data compression is a reduction in the number of bits needed to represent data.
Compressing data can save storage capacity, speed up file transfer and decrease
costs for storage hardware and network bandwidth.

You might also like