Unit-2 Python
Unit-2 Python
Unit-2 Python
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
amount = 10000
if(amount>2999)
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
marks = 10000
a = marks / 0
print(a)
Output:
marks = 10000
a = marks / 0
print(a)
Output:
Error Handling
When an error and an exception are raised then we handle that with the help of the
Handling method.
try:
print("code start")
print(1 / 0)
except:
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:
amount = 1999
else:
except ValueError as e:
print(e)
Output:
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
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
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
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
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
file = open('geek.txt','w')
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
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.close()
Output:
This is the write commandIt allows us to write in a particular fileThis will add this line
Python Classes/Objects
Create a Class
Prog:
class MyClass:
x=5
print(x)
print("Class is a blueprint")
Output:
5
Class is a blueprint
Create Object
class MyClass:
x=5
p1 = MyClass()
print(p1.x)
Output:
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.
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()
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
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...
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.
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
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):
yield i*i
a = sq_numbers(3)
print(next(a))
print(next(a))
Output:
The square of numbers 1,2,3 are :
1
4
9
Function is used to
Class is used to implement an iterator
implement a generator.
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
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
Output :
True
False
False