Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Unit6 Python Class

A

Uploaded by

a123000000s
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit6 Python Class

A

Uploaded by

a123000000s
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 39

{

"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "a_F71HyM9i4T"
},
"source": [
"**Class:** \n",
"\n",
"A class is a blueprint or template that defines the properties
(attributes) and behaviors (methods) that objects of that class will have. It acts
as a blueprint for creating objects.\n",
"\n",
"\n",
"---\n",
"\n",
"**Object:** \n",
"\n",
"An object is an instance of a class. It is a concrete representation of
the class, created using the class blueprint. Objects have their own unique set of
attributes and can perform actions defined by the class methods.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "D9KduZxRpzPj"
},
"outputs": [],
"source": [
"#https://pynative.com/python-inheritance/"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "542x9rfN-A7J",
"outputId": "b4bc107c-0068-4401-99d5-74f47d147c88"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Toyota\n",
"Camry\n",
"The Toyota Camry is driving.\n"
]
}
],
"source": [
"class Car:\n",
" def __init__(self, make, model):\n",
" self.make = make\n",
" self.model = model\n",
"\n",
" def drive(self):\n",
" print(f\"The {self.make} {self.model} is driving.\")\n",
"\n",
"# Creating an object of the Car class\n",
"my_car = Car(\"Toyota\", \"Camry\")\n",
"\n",
"# Accessing object attributes\n",
"print(my_car.make) # Output: Toyota\n",
"print(my_car.model) # Output: Camry\n",
"\n",
"# Calling object methods\n",
"my_car.drive() # Output: The Toyota Camry is driving.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "UMfC8hcFAleu"
},
"source": [
"**To create an object in Python, you need to follow these steps:**\n",
"\n",
"**Define a class:** \n",
"\n",
"First, define a class that serves as a blueprint for the object. The class
defines the attributes and behaviors that the object will have.\n",
"\n",
"\n",
"---\n",
"\n",
"\n",
"**Instantiate the object:**\n",
"\n",
"To create an object based on the class, you need to instantiate it.
Instantiation is the process of creating a specific instance of the class."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "uTwCsIUGAkc3",
"outputId": "5f80a646-360d-4755-c2cc-a985407a984a"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Alice\n",
"25\n",
"Hello, my name is Alice.\n"
]
}
],
"source": [
"class Person:\n",
" def __init__(self, name, age):\n",
" self.name = name\n",
" self.age = age\n",
"\n",
" def say_hello(self):\n",
" print(f\"Hello, my name is {self.name}.\")\n",
"\n",
"# Create an object of the Person class\n",
"person1 = Person(\"Alice\", 25)\n",
"\n",
"# Access object attributes\n",
"print(person1.name) # Output: Alice\n",
"print(person1.age) # Output: 25\n",
"\n",
"# Call object methods\n",
"person1.say_hello() # Output: Hello, my name is Alice.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Arh_euItJRgz"
},
"outputs": [],
"source": [
"# To create an object in Python\n",
"# Define a class\n",
"class MyClass:\n",
" def __init__(self, parameter1, parameter2):\n",
" self.parameter1 = parameter1\n",
" self.parameter2 = parameter2\n",
"\n",
" def my_method(self):\n",
" print(\"Hello, I'm a method of MyClass!\")\n",
"\n",
"# Create an instance of the class\n",
"my_object = MyClass(\"value1\", \"value2\")\n",
"\n",
"# Access object attributes\n",
"print(my_object.parameter1)\n",
"print(my_object.parameter2)\n",
"\n",
"# Call object methods\n",
"my_object.my_method()\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "kPzOYdBnJUwn",
"outputId": "116feec5-376f-4f2e-a03b-274ecc93e2a8"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Abhijit\n",
"BTech\n",
"21\n",
"Name : Abhijit\n",
"Education : BTech\n",
"Age : 21\n"
]
}
],
"source": [
"# Class example\n",
"\n",
"class Person:\n",
" def __init__(self, name, education, age):\n",
" self.name = name\n",
" self.education = education\n",
" self.age = age\n",
"\n",
"# method\n",
" def person_details(self):\n",
" print(f\"Name : {self.name}\")\n",
" print(f\"Education : {self.education}\")\n",
" print(f\"Age : {self.age}\")\n",
" \n",
"# object\n",
"p = Person(\"Abhijit\", \"BTech\", 21)\n",
"\n",
"# Accessing object \n",
"print(p.name)\n",
"print(p.education)\n",
"print(p.age)\n",
"\n",
"# Access method\n",
"p.person_details()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "X7-nolEhYhsA",
"outputId": "5e73656b-a6a6-4365-b088-67c8069fda07"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Abhijit\n",
"BTech\n",
"21\n",
"Name : Abhijit\n",
"Education : BTech\n",
"Age : 21\n",
"Manmath\n",
"BTech\n",
"21\n",
"Name : Manmath\n",
"Education : BTech\n",
"Age : 21\n"
]
}
],
"source": [
"# Class example\n",
"\n",
"class Person:\n",
" def __init__(self, name, education, age):\n",
" self.name = name\n",
" self.education = education\n",
" self.age = age\n",
"\n",
"# method\n",
" def person_details(self):\n",
" print(f\"Name : {self.name}\")\n",
" print(f\"Education : {self.education}\")\n",
" print(f\"Age : {self.age}\")\n",
" \n",
"# object\n",
"p1 = Person(\"Abhijit\", \"BTech\", 21)\n",
"p2 = Person(\"Manmath\", \"BTech\", 21)\n",
"\n",
"# Accessing object \n",
"print(p1.name)\n",
"print(p1.education)\n",
"print(p1.age)\n",
"\n",
"# Access method\n",
"p1.person_details()\n",
"\n",
"# Accessing object \n",
"print(p2.name)\n",
"print(p2.education)\n",
"print(p2.age)\n",
"\n",
"# Access method\n",
"p2.person_details()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "ff3KV8uJZCwg",
"outputId": "fe8c9691-0b0d-4bfa-f93a-f4e5d64fffd8"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter the name : yogesh\n",
"Enter the education : b.tech\n",
"Enter the age : 22\n",
"yogesh\n",
"b.tech\n",
"22\n",
"Name : yogesh\n",
"Education : b.tech\n",
"Age : 22\n"
]
}
],
"source": [
"# Class example\n",
"\n",
"class Person:\n",
" def __init__(self, name, education, age):\n",
" self.name = name\n",
" self.education = education\n",
" self.age = age\n",
"\n",
"# method\n",
" def person_details(self):\n",
" print(f\"Name : {self.name}\")\n",
" print(f\"Education : {self.education}\")\n",
" print(f\"Age : {self.age}\")\n",
" \n",
"x = input(\"Enter the name : \")\n",
"y = input(\"Enter the education : \")\n",
"z = int(input(\"Enter the age : \"))\n",
"\n",
"# object\n",
"p1 = Person(x,y,z)\n",
"\n",
"\n",
"# Accessing object \n",
"print(p1.name)\n",
"print(p1.education)\n",
"print(p1.age)\n",
"\n",
"# Access method\n",
"p1.person_details()\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "7wTvZHNkbF_C",
"outputId": "91e43c13-b8f8-4888-a013-bce20143d1f0"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter the first number : 12\n",
"Enter the second number : 12\n"
]
},
{
"data": {
"text/plain": [
"24"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Sum\n",
"\n",
"class Num:\n",
" def __init__(self, num1, num2):\n",
" self.num1 = num1\n",
" self.num2 = num2\n",
"\n",
" def sum(self):\n",
" add = self.num1 + self.num2\n",
" return add\n",
"\n",
"a = int(input(\"Enter the first number : \"))\n",
"b = int(input(\"Enter the second number : \"))\n",
"\n",
"n = Num(a,b)\n",
"\n",
"n.sum()\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "otMDdCXLeo1b",
"outputId": "63bbec0b-b384-4d12-d7fa-ab4626bfed2a"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter the number : 5\n",
"Square of 5 = 25\n",
"Cube of 5 = 125\n"
]
}
],
"source": [
"# Multiple method\n",
"class Calci:\n",
" def __init__(self, number):\n",
" self.number = number\n",
" \n",
" def square(self):\n",
" print(f\"Square of {self.number} = {self.number**2}\")\n",
" \n",
" def cube(self):\n",
" print(f\"Cube of {self.number} = {self.number**3}\")\n",
"\n",
"num1 = int(input(\"Enter the number : \"))\n",
"\n",
"n1 = Calci(num1)\n",
"\n",
"n1.square()\n",
"n1.cube()\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "V4zD-1Y9g5QE"
},
"source": [
"**Python Inheritance**\n",
"\n",
"Inheritance allows us to define a class that inherits all the methods and
properties from another class.\n",
"\n",
"Parent class is the class being inherited from, also called base class.\
n",
"\n",
"Child class is the class that inherits from another class, also called
derived class."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "0jXaq3WGgfDr",
"outputId": "b48b07fa-a264-48d1-af05-e7683c91d653"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"John Doe\n"
]
}
],
"source": [
"# Create a class named Person, with firstname and lastname properties, and
a printname method:\n",
"class Person:\n",
" def __init__(self, fname, lname):\n",
" self.firstname = fname\n",
" self.lastname = lname\n",
"\n",
" def printname(self):\n",
" print(self.firstname, self.lastname)\n",
"\n",
"#Use the Person class to create an object, and then execute the printname
method:\n",
"\n",
"x = Person(\"John\", \"Doe\")\n",
"x.printname()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4bEB7AgUiG2o"
},
"source": [
"**Create a Child Class**\n",
"\n",
"To create a class that inherits the functionality from another class, send
the parent class as a parameter when creating the child class:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "yhjTe72_iXTr",
"outputId": "512dd22f-7776-4c55-c966-1900475271a6"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"John Doe\n",
"Mike Olsen\n"
]
}
],
"source": [
"# Create a class named Person, with firstname and lastname properties, and
a printname method:\n",
"class Person:\n",
" def __init__(self, fname, lname):\n",
" self.firstname = fname\n",
" self.lastname = lname\n",
"\n",
" def printname(self):\n",
" print(self.firstname, self.lastname)\n",
"\n",
"#Use the Person class to create an object, and then execute the printname
method:\n",
"\n",
"x = Person(\"John\", \"Doe\")\n",
"x.printname()\n",
"\n",
"# Create a class named Student, which will inherit the properties and
methods from the Person class:\n",
"class Student(Person):\n",
" pass\n",
"\n",
"# Use the Student class to create an object, and then execute the
printname method:\n",
"x = Student(\"Mike\", \"Olsen\")\n",
"x.printname()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"background_save": true,
"base_uri": "https://localhost:8080/"
},
"id": "2d8HH1FNjU8l",
"outputId": "8293a6a5-1ea6-41f7-a459-5099054d5cb0"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"I can eat\n",
"My name is Moti\n"
]
}
],
"source": [
"# Single inheritance\n",
" \n",
"class Animal:\n",
" \n",
" def eat(self):\n",
" print(\"I can eat\")\n",
"\n",
"# inherit from Animal\n",
"class Dog(Animal):\n",
" def __init__(self, name):\n",
" self.name = name\n",
"\n",
" # new method in subclass\n",
" def display(self):\n",
" # access name attribute of superclass using self\n",
" print(\"My name is \", self.name)\n",
"\n",
"# create an object of the subclass\n",
"labrador = Dog(\"Moti\")\n",
"\n",
"# access superclass attribute and method \n",
"#labrador.name = \"Rohu\"\n",
"labrador.eat()\n",
"\n",
"# call subclass method \n",
"labrador.display()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "UFcaKUDknuP2",
"outputId": "449e10b8-df5c-4cde-a469-eff43f827e4a"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Inside Vehicle class\n",
"Inside Car class\n"
]
}
],
"source": [
"# Base class\n",
"class Vehicle:\n",
" def Vehicle_info(self):\n",
" print('Inside Vehicle class')\n",
"\n",
"# Child class\n",
"class Car(Vehicle):\n",
" def car_info(self):\n",
" print('Inside Car class')\n",
"\n",
"# Create object of Car\n",
"car = Car()\n",
"\n",
"# access Vehicle's info using car object\n",
"car.Vehicle_info()\n",
"car.car_info()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "JYi-FwGkoepX",
"outputId": "137dfa35-5373-4421-a331-c1a675ae7ace"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Inside Person class\n",
"Name: Jessa Age: 28\n",
"Inside Company class\n",
"Name: Google location: Atlanta\n",
"Inside Employee class\n",
"Salary: 12000 Skill: Machine Learning\n"
]
}
],
"source": [
"# Multiple Inheritance\n",
"\n",
"# In multiple inheritance, one child class can inherit from multiple
parent classes. So here is one child class and multiple parent classes\n",
"\n",
"# Parent class 1\n",
"class Person:\n",
" def person_info(self, name, age):\n",
" print('Inside Person class')\n",
" print('Name:', name, 'Age:', age)\n",
"\n",
"# Parent class 2\n",
"class Company:\n",
" def company_info(self, company_name, location):\n",
" print('Inside Company class')\n",
" print('Name:', company_name, 'location:', location)\n",
"\n",
"# Child class\n",
"class Employee(Person, Company):\n",
" def Employee_info(self, salary, skill):\n",
" print('Inside Employee class')\n",
" print('Salary:', salary, 'Skill:', skill)\n",
"\n",
"# Create object of Employee\n",
"emp = Employee()\n",
"\n",
"# access data\n",
"emp.person_info('Jessa', 28)\n",
"emp.company_info('Google', 'Atlanta')\n",
"emp.Employee_info(12000, 'Machine Learning')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "OiaqgY9gox_S",
"outputId": "eb23f5a4-0fb6-4802-e6d0-cdbbfcc6a680"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Inside Vehicle class\n",
"Inside Car class\n",
"Inside SportsCar class\n"
]
}
],
"source": [
"# Multilevel inheritance\n",
"# In multilevel inheritance, a class inherits from a child class or
derived class. Suppose three classes A, B, C. A is the superclass, \n",
"# B is the child class of A, C is the child class of B. In other words, we
can say a chain of classes is called multilevel inheritance.\n",
"\n",
"# Base class\n",
"class Vehicle:\n",
" def Vehicle_info(self):\n",
" print('Inside Vehicle class')\n",
"\n",
"# Child class\n",
"class Car(Vehicle):\n",
" def car_info(self):\n",
" print('Inside Car class')\n",
"\n",
"# Child class\n",
"class SportsCar(Car):\n",
" def sports_car_info(self):\n",
" print('Inside SportsCar class')\n",
"\n",
"# Create object of SportsCar\n",
"s_car = SportsCar()\n",
"\n",
"# access Vehicle's and Car info using SportsCar object\n",
"s_car.Vehicle_info()\n",
"s_car.car_info()\n",
"s_car.sports_car_info()\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "Y2cwebRnpCRc",
"outputId": "8ea06906-ddd5-41c1-eb70-954c81f33622"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is Vehicle\n",
"Car name is: BMW\n",
"This is Vehicle\n",
"Truck name is: Ford\n"
]
}
],
"source": [
"# Hierarchical Inheritance\n",
"# In Hierarchical inheritance, more than one child class is derived from a
single parent class. In other words, we can say one parent class \n",
"# and multiple child classes.\n",
"\n",
"class Vehicle:\n",
" def info(self):\n",
" print(\"This is Vehicle\")\n",
"\n",
"class Car(Vehicle):\n",
" def car_info(self, name):\n",
" print(\"Car name is:\", name)\n",
"\n",
"class Truck(Vehicle):\n",
" def truck_info(self, name):\n",
" print(\"Truck name is:\", name)\n",
"\n",
"obj1 = Car()\n",
"obj1.info()\n",
"obj1.car_info('BMW')\n",
"\n",
"obj2 = Truck()\n",
"obj2.info()\n",
"obj2.truck_info('Ford')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "GYyWP0ELpNwm",
"outputId": "16fe4cee-b3fb-4d6b-b1cc-6044952fc675"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Inside Vehicle class\n",
"Inside Car class\n",
"Inside SportsCar class\n"
]
}
],
"source": [
"# Hybrid Inheritance\n",
"# When inheritance is consists of multiple types or a combination of
different inheritance is called hybrid inheritance.\n",
"\n",
"class Vehicle:\n",
" def vehicle_info(self):\n",
" print(\"Inside Vehicle class\")\n",
"\n",
"class Car(Vehicle):\n",
" def car_info(self):\n",
" print(\"Inside Car class\")\n",
"\n",
"class Truck(Vehicle):\n",
" def truck_info(self):\n",
" print(\"Inside Truck class\")\n",
"\n",
"# Sports Car can inherits properties of Vehicle and Car\n",
"class SportsCar(Car, Vehicle):\n",
" def sports_car_info(self):\n",
" print(\"Inside SportsCar class\")\n",
"\n",
"# create object\n",
"s_car = SportsCar()\n",
"\n",
"s_car.vehicle_info()\n",
"s_car.car_info()\n",
"s_car.sports_car_info()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6IAw3yUktpHR"
},
"source": [
"**Set**\n",
"\n",
"---\n",
"\n",
"\n",
"\n",
"* Sets are used to store multiple items in a single variable.\n",
"* A set is a collection which is unordered, unchangeable, and unindexed.\
n",
"* Set items are unchangeable, but you can remove items and add new items.\
n",
"* Sets are written with curly brackets.\n",
"* Set items do not allow duplicate values.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "M-jGUf85pkwJ",
"outputId": "43c02a4f-0260-4e31-d8fc-e5ecab55a7b8"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{True, 'MIT', 'A', 25.6, (2+3j), 15}\n",
"<class 'set'>\n"
]
}
],
"source": [
"# create set\n",
"s1 = {\"MIT\", 15, 25.6, 2+3j, True, \"A\"}\n",
"print(s1)\n",
"\n",
"print(type(s1))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "ZHSi_0pUwYKR",
"outputId": "55ae535b-839b-4d5c-d0ec-630b05215a70"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'a', 'c', 'b'}\n"
]
}
],
"source": [
"# duplicate values not allowed\n",
"s2 = {\"a\", \"a\", \"b\", \"c\"}\n",
"print(s2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "h4Khfv1JxBAH",
"outputId": "849628c5-845f-4ad2-97ad-ddf9cb461967"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{True, 2}\n"
]
}
],
"source": [
"# True and 1\n",
"s3 = {True, 1, 2}\n",
"print(s3)"
]
},
{
"cell_type": "markdown",
"source": [
"**Python Exception**\n",
"\n",
"\n",
"---\n",
"\n",
"* The try block lets you test a block of code for errors.\n",
"\n",
"* The except block lets you handle the error.\n",
"\n",
"* The else block lets you execute code when there is no error.\n",
"\n",
"* The finally block lets you execute code, regardless of the result of the
try- and except blocks.\n",
"\n",
"**Exception Handling**\n",
"\n",
"\n",
"---\n",
"\n",
"\n",
"When an error occurs, or exception as we call it, Python will normally
stop and generate an error message.\n",
"\n",
"**SyntaxError:** \n",
"\n",
"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.\n",
"\n",
"**TypeError:** \n",
"\n",
"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.\n",
"\n",
"**NameError:** \n",
"\n",
"This exception is raised when a variable or function name is not found in
the current scope.\n",
"\n",
"**IndexError:** \n",
"\n",
"This exception is raised when an index is out of range for a list, tuple,
or other sequence types.\n",
"\n",
"**KeyError:** \n",
"\n",
"This exception is raised when a key is not found in a dictionary.\n",
"\n",
"**ValueError:** \n",
"\n",
"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.\n",
"\n",
"**AttributeError:**\n",
"\n",
"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.\n",
"\n",
"**IOError:** \n",
"\n",
"This exception is raised when an I/O operation, such as reading or writing
a file, fails due to an input/output error.\n",
"\n",
"**ZeroDivisionError:** \n",
"\n",
"This exception is raised when an attempt is made to divide a number by
zero.\n",
"\n",
"**ImportError:** \n",
"\n",
"This exception is raised when an import statement fails to find or load a
module."
],
"metadata": {
"id": "qTBPTmcZ4ofV"
}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Zi_7WlS_xkii",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "e282db67-baa0-442e-c097-cffd1d5e4101"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"5\n"
]
}
],
"source": [
"x=5\n",
"try:\n",
" print(x)\n",
"except:\n",
" print(\"An exception occurred\")"
]
},
{
"cell_type": "code",
"source": [
"# Print one message if the try block raises a NameError and another for
other errors:\n",
"\n",
"try:\n",
" print(y)\n",
"except NameError:\n",
" print(\"Variable y is not defined\")\n",
"except:\n",
" print(\"Something else went wrong\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "0b31JUHU5XQ4",
"outputId": "a9339472-9cd9-4d64-9a06-49a857612d57"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Variable y is not defined\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# In this example, the try block does not generate any error:\n",
"try:\n",
" print(\"hello\")\n",
"except:\n",
" print(\"Something went wrong\")\n",
"else:\n",
" print(\"Nothing went wrong\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "flkC1IpI5rVj",
"outputId": "9604f654-6e19-4a64-b597-6a6d15ffe370"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"hello\n",
"Nothing went wrong\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# In this example, the try block does not generate any error:\n",
"try:\n",
" print(\"Hello\")\n",
"except:\n",
" print(x)\n",
"else:\n",
" print(\"Nothing went wrong\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "rQDZ9ND26E9w",
"outputId": "276a2bf2-1c94-40bf-88e4-f894c1c86d13"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Hello\n",
"Nothing went wrong\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# The finally block, if specified, will be executed regardless if the try
block raises an error or not.\n",
"try:\n",
" print(\"Hello\")\n",
"except:\n",
" print(\"Something went wrong\")\n",
"finally:\n",
" print(\"The 'try except' is finished\")\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "wApthP_v6OU7",
"outputId": "434abefa-c6d0-47dd-da20-31c1dab2695a"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Hello\n",
"The 'try except' is finished\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# Try to open and write to a file that is not writable:\n",
"try:\n",
" f = open(\"demofile.txt\")\n",
" try:\n",
" f.write(\"Lorum Ipsum\")\n",
" except:\n",
" print(\"Something went wrong when writing to the file\")\n",
" finally:\n",
" f.close()\n",
"except:\n",
" print(\"Something went wrong when opening the file\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "ew-psnFR6TQz",
"outputId": "7a0c6f6e-afa8-41d6-cc4e-c6349d1c6699"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Something went wrong when opening the file\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# Raise an error and stop the program if x is lower than 0:\n",
"x = -2\n",
"\n",
"if x < 0:\n",
" raise Exception(\"Sorry, no numbers below zero\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 201
},
"id": "-pZxMIyM6kRT",
"outputId": "070d148d-7454-43b8-83f6-18ac4c5a496d"
},
"execution_count": null,
"outputs": [
{
"output_type": "error",
"ename": "Exception",
"evalue": "ignored",
"traceback": [
"\
u001b[0;31m------------------------------------------------------------------------
---\u001b[0m",
"\u001b[0;31mException\u001b[0m
Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-12-3ad4dbfaa24e>\u001b[0m in \
u001b[0;36m<cell line: 4>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 3\u001b[0m \
u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;32mif\u001b[0m
\u001b[0mx\u001b[0m \u001b[0;34m<\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m:\
u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\
u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mException\u001b[0m\u001b[0;34m(\
u001b[0m\u001b[0;34m\"Sorry, no numbers below zero\"\u001b[0m\u001b[0;34m)\
u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mException\u001b[0m: Sorry, no numbers below zero"
]
}
]
},
{
"cell_type": "code",
"source": [
"# Raise a TypeError if x is not an integer:\n",
"# Raise keeword is used to raise exception\n",
"x = \"mit\"\n",
"print(type(x))\n",
"if not type(x) is int:\n",
" raise TypeError(\"Only integers are allowed\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 218
},
"id": "qSwJJDNf62bE",
"outputId": "14d62a70-d46c-41a1-b96a-affe0abfc8f2"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"<class 'str'>\n"
]
},
{
"output_type": "error",
"ename": "TypeError",
"evalue": "ignored",
"traceback": [
"\
u001b[0;31m------------------------------------------------------------------------
---\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m
Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-15-b7cce8214c98>\u001b[0m in \
u001b[0;36m<cell line: 5>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 4\u001b[0m \
u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtype\u001b[0m\u001b[0;34m(\
u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\
u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \
u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mtype\u001b[0m\
u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mis\
u001b[0m \u001b[0mint\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\
u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 6\u001b[0;31m \u001b[0;32mraise\
u001b[0m \u001b[0mTypeError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Only
integers are allowed\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\
u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m: Only integers are allowed"
]
}
]
},
{
"cell_type": "code",
"source": [
"# initialize the amount variable\n",
"# syntax error\n",
"amount = 10000\n",
"\n",
"# check that You are eligible to\n",
"# purchase Dsa Self Paced or not\n",
"if(amount > 2999)\n",
"print(\"You are eligible to purchase Dsa Self Paced\")\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "2w7qXrDI8AuI",
"outputId": "f0656ff4-dd8d-4422-981a-0a878cf3de19"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"You are eligible to purchase Dsa Self Paced\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# initialize the amount variable\n",
"marks = 10000\n",
"\n",
"# perform division with 0\n",
"a = marks / 0\n",
"print(a)\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 218
},
"id": "nenhXjwR8Ebl",
"outputId": "ce6cf7ba-f17b-4088-a42f-e501622fbdc7"
},
"execution_count": null,
"outputs": [
{
"output_type": "error",
"ename": "ZeroDivisionError",
"evalue": "ignored",
"traceback": [
"\
u001b[0;31m------------------------------------------------------------------------
---\u001b[0m",
"\u001b[0;31mZeroDivisionError\u001b[0m
Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-19-5f312778a383>\u001b[0m in \
u001b[0;36m<cell line: 5>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 3\u001b[0m \
u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;31m# perform
division with 0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\
u001b[0;32m----> 5\u001b[0;31m \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \
u001b[0mmarks\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m\
u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 6\u001b[0m \
u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\
u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mZeroDivisionError\u001b[0m: division by zero"
]
}
]
},
{
"cell_type": "code",
"source": [
"x = 5\n",
"print(type(x))\n",
"y = \"hello\"\n",
"print(type(y))\n",
"z = x + y # Raises a TypeError: unsupported operand type(s) for +: 'int'
and 'str'\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 253
},
"id": "36l36jSE8LCf",
"outputId": "e82c6dc0-789a-4c27-9a01-d811c3b78e62"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"<class 'int'>\n",
"<class 'str'>\n"
]
},
{
"output_type": "error",
"ename": "TypeError",
"evalue": "ignored",
"traceback": [
"\
u001b[0;31m------------------------------------------------------------------------
---\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m
Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-20-027956f862fb>\u001b[0m in \
u001b[0;36m<cell line: 5>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 3\u001b[0m \
u001b[0my\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m\"hello\"\u001b[0m\
u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \
u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtype\u001b[0m\u001b[0;34m(\
u001b[0m\u001b[0my\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\
u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m
\u001b[0mz\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mx\u001b[0m \u001b[0;34m+\
u001b[0m \u001b[0my\u001b[0m \u001b[0;31m# Raises a TypeError: unsupported operand
type(s) for +: 'int' and 'str'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\
u001b[0m\n\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for +:
'int' and 'str'"
]
}
]
},
{
"cell_type": "code",
"source": [
"x = 5\n",
"y = \"hello\"\n",
"try:\n",
"\tz = x + y\n",
"except TypeError:\n",
"\tprint(\"Error: cannot add an int and a str\")\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "C8azspDk8Oyc",
"outputId": "92643e67-b42d-4e76-e36e-d4e5ccd9fdd2"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Error: cannot add an int and a str\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# Python program to handle simple runtime error\n",
"#Python 3\n",
"\n",
"a = [1, 2, 3]\n",
"try:\n",
"\tprint (\"Second element = %d\" %(a[1]))\n",
"\n",
"\t# Throws error since there are only 3 elements in array\n",
"\tprint (\"Fourth element = %d\" %(a[3]))\n",
"\n",
"except:\n",
"\tprint (\"An error occurred\")\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "dDqBDQZe8S8D",
"outputId": "bd957c5c-5f1d-4e02-94ab-384a4aeed401"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Second element = 2\n",
"An error occurred\n"
]
}
]
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "OxzD-8LQngEz"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"**Catching Specific Exception**\n",
"\n",
"---\n",
"\n",
"\n",
"A try statement can have more than one except clause, to specify handlers
for different exceptions. Please note that at most one handler will be executed.
For example, we can add IndexError in the above code. The general syntax for adding
specific exceptions are – \n",
"\n",
"try:\n",
" # statement(s)\n",
"except IndexError:\n",
" # statement(s)\n",
"except ValueError:\n",
" # statement(s)"
],
"metadata": {
"id": "A7UK2Mg_8XXF"
}
},
{
"cell_type": "code",
"source": [
"# Program to handle multiple errors with one\n",
"# except statement\n",
"# Python 3\n",
"\n",
"def fun(a):\n",
"\tif a < 4:\n",
"\n",
"\t\t# throws ZeroDivisionError for a = 3\n",
"\t\tb = a/(a-3)\n",
"\n",
"\t# throws NameError if a >= 4\n",
"\tprint(\"Value of b = \", b)\n",
"\t\n",
"try:\n",
"\tfun(3)\n",
"\tfun(5)\n",
"\n",
"# note that braces () are necessary here for\n",
"# multiple exceptions\n",
"except ZeroDivisionError:\n",
"\tprint(\"ZeroDivisionError Occurred and Handled\")\n",
"except NameError:\n",
"\tprint(\"NameError Occurred and Handled\")\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "dD4cK-hs8jsp",
"outputId": "aefdd465-89c5-412a-ce0f-51099f87c6ec"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"ZeroDivisionError Occurred and Handled\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"def check(a):\n",
" if a<4:\n",
" print(\"a is less than 4\")\n",
" try:\n",
" b=a/(a-3)\n",
" print(b)\n",
" except ZeroDivisionError:\n",
" print(\"zeroDivisionerror\")\n",
" finally:\n",
" print(\"exception handle\")\n",
"\n",
"check(1)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "bsK9eoYvnjaO",
"outputId": "cdcbfa1c-268f-4142-c56e-058435cbbf8c"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"a is less than 4\n",
"-0.5\n",
"exception handle\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# Program to depict else clause with try-except\n",
"# Python 3\n",
"# Function which returns a/b\n",
"def AbyB(a , b):\n",
"\ttry:\n",
"\t\tc = ((a+b) / (a-b))\n",
"\texcept ZeroDivisionError:\n",
"\t\tprint (\"a/b result in 0\")\n",
"\telse:\n",
"\t\tprint (c)\n",
"\n",
"# Driver program to test above function\n",
"AbyB(2.0, 3.0)\n",
"AbyB(3.0, 3.0)\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "3c84EG-I8pC5",
"outputId": "013075ab-106c-43f6-ab60-0dd57bfb6b3d"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"-5.0\n",
"a/b result in 0\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"**Finally Keyword in Python**\n",
"\n",
"---\n",
"\n",
"\n",
"Python provides a keyword finally, which is always executed after the try
and except blocks. The final block always executes after the normal termination of
the try block or after the try block terminates due to some exception.\n",
"\n",
"Syntax:\n",
"\n",
"try:\n",
" # Some Code.... \n",
"\n",
"except:\n",
" # optional block\n",
" # Handling of exception (if required)\n",
"\n",
"else:\n",
" # execute if no exception\n",
"\n",
"finally:\n",
" # Some code .....(always executed)"
],
"metadata": {
"id": "H4frJmu58tEC"
}
},
{
"cell_type": "code",
"source": [
"# Python program to demonstrate finally\n",
"\n",
"# No exception Exception raised in try block\n",
"try:\n",
"\tk = 5//0 # raises divide by zero exception.\n",
"\tprint(k)\n",
"\n",
"# handles zerodivision exception\n",
"except ZeroDivisionError:\n",
"\tprint(\"Can't divide by zero\")\n",
"\n",
"finally:\n",
"\t# this block is always executed\n",
"\t# regardless of exception generation.\n",
"\tprint('This is always executed')\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "IKl73NIH8zao",
"outputId": "40a0923b-69b2-4a58-f2d5-bcc711ca1b45"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Can't divide by zero\n",
"This is always executed\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"**Raising Exception**\n",
"\n",
"---\n",
"\n",
"\n",
"The raise statement allows the programmer to force a specific exception to
occur. The sole argument in raise indicates the exception to be raised. This must
be either an exception instance or an exception class (a class that derives from
Exception)."
],
"metadata": {
"id": "A44iHSMi85hL"
}
},
{
"cell_type": "code",
"source": [
"# Program to depict Raising Exception\n",
"\n",
"try:\n",
"\traise NameError(\"Hi there\") # Raise Error\n",
"except NameError:\n",
"\tprint (\"An exception\")\n",
"\traise # To determine whether the exception was raised or not\n"
],
"metadata": {
"id": "TSv481dH8-RT",
"outputId": "7bab7f3c-19d5-43d1-b782-968ede8cb21e",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 253
}
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"An exception\n"
]
},
{
"output_type": "error",
"ename": "NameError",
"evalue": "ignored",
"traceback": [
"\
u001b[0;31m------------------------------------------------------------------------
---\u001b[0m",
"\u001b[0;31mNameError\u001b[0m
Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-42-87bf2bdaba1c>\u001b[0m in \
u001b[0;36m<cell line: 3>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 2\u001b[0m \
u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mtry\
u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\
n\u001b[0;32m----> 4\u001b[0;31m \u001b[0;32mraise\u001b[0m \
u001b[0mNameError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Hi there\"\u001b[0m\
u001b[0;34m)\u001b[0m \u001b[0;31m# Raise Error\u001b[0m\u001b[0;34m\u001b[0m\
u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \
u001b[0;32mexcept\u001b[0m \u001b[0mNameError\u001b[0m\u001b[0;34m:\u001b[0m\
u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m
\u001b[0mprint\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;34m\"An exception\"\
u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\
n",
"\u001b[0;31mNameError\u001b[0m: Hi there"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"Advantages of Exception Handling:\n",
"Improved program reliability: By handling exceptions properly, you can
prevent your program from crashing or producing incorrect results due to unexpected
errors or input.\n",
"Simplified error handling: Exception handling allows you to separate error
handling code from the main program logic, making it easier to read and maintain
your code.\n",
"Cleaner code: With exception handling, you can avoid using complex
conditional statements to check for errors, leading to cleaner and more readable
code.\n",
"Easier debugging: When an exception is raised, the Python interpreter
prints a traceback that shows the exact location where the exception occurred,
making it easier to debug your code.\n",
"Disadvantages of Exception Handling:\n",
"Performance overhead: Exception handling can be slower than using
conditional statements to check for errors, as the interpreter has to perform
additional work to catch and handle the exception.\n",
"Increased code complexity: Exception handling can make your code more
complex, especially if you have to handle multiple types of exceptions or implement
complex error handling logic.\n",
"Possible security risks: Improperly handled exceptions can potentially
reveal sensitive information or create security vulnerabilities in your code, so
it’s important to handle exceptions carefully and avoid exposing too much
information about your program."
],
"metadata": {
"id": "xg5o30LH9E3U"
}
},
{
"cell_type": "markdown",
"source": [],
"metadata": {
"id": "yxS1ZR9-dD3h"
}
},
{
"cell_type": "code",
"source": [
"from google.colab import drive\n",
"drive.mount('/drive')"
],
"metadata": {
"id": "r4J38lWU9EM7",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "a7b0235c-770f-4ca6-fb81-c385c9f9047e"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Mounted at /drive\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"import os\n",
"file = open('/drive/My Drive/Colab Notebooks/data.txt','w')\n",
"file.write('Hello Students\\n')\n",
"file.write('Welcome to my class')\n",
"file.close()"
],
"metadata": {
"id": "QTEslqrqbTBS"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"file = open('/drive/My Drive/Colab Notebooks/data.txt','r')\n",
"res = file.read()\n",
"print(res)\n",
"file.close()"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "F1gaM7lCbpmo",
"outputId": "70928b9a-fffe-4cf5-fef6-a8547b080be2"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Hello Students\n",
"Welcome to my class\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# Opening the file for writing\n",
"file = open('/drive/My Drive/Colab Notebooks/data.txt','w')\n",
"file.write('Dear Students\\n')\n",
"file.write('This is file handling ')\n",
"file.write(\"bhakti\\n\")\n",
"file.close()\n",
"\n",
"# Opening the file for reading\n",
"file = open('/drive/My Drive/Colab Notebooks/data.txt','r')\n",
"res = file.read()\n",
"print(res)\n",
"file.close()"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "tlKmsBxObxoL",
"outputId": "0bbe8ab3-2987-4ced-8d43-d37cfbbc6f14"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Dear Students\n",
"This is file handling bhakti\n",
"\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# Opening the file data.txt in append mode to add extra information\n",
"file = open('/drive/My Drive/Colab Notebooks/data.txt','a')\n",
"file.write('We are learning Text File operations\\n')\n",
"file.write('This is really interesting')\n",
"file.close()\n",
"\n",
"# Opening the file for reading\n",
"file = open('/drive/My Drive/Colab Notebooks/data.txt','r')\n",
"res = file.read()\n",
"print(res)\n",
"file.close()"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "pgUhmCQ9b8G8",
"outputId": "82cc738f-a9a0-40a7-decb-735c0af3c40f"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Dear Students\n",
"This is file handling bhakti\n",
"We are learning Text File operations\n",
"This is really interesting\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"file = open('/drive/My Drive/Colab Notebooks/data.txt','r')\n",
"res = file.read(5)\n",
"print(res)\n",
"res = file.read(5)\n",
"print(res)\n",
"res = file.read(3)\n",
"print(res)\n",
"res = file.read(2)\n",
"print(res)\n",
"file.close()"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "RdejaK-Db-PZ",
"outputId": "51833f2b-c122-427a-c90b-d70d8fee3a26"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Dear \n",
"Stude\n",
"nts\n",
"\n",
"T\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"file = open('/drive/My Drive/Colab Notebooks/data.txt','r')\n",
"res = file.readline() # Reading a single line as a string\n",
"print(res)\n",
"res = file.readline() # Reading the next line in the file\n",
"print(res)\n",
"file.close()"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "kp5B99lXcE_S",
"outputId": "263416d6-196c-43cc-b478-a333e19e4486"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Dear Students\n",
"\n",
"This is file handling bhakti\n",
"\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"file = open('/drive/My Drive/Colab Notebooks/data.txt','r')\n",
"res = file.readline(7) # Reading first 7 characters from the first line\
n",
"print(res)\n",
"res = file.readline(10) # Reading remaining chareacters from the first
line\n",
"print(res)\n",
"file.close()"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "GKtLhT5scMh8",
"outputId": "bf2dfaa6-78f0-4d60-be16-93adde371079"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Dear St\n",
"udents\n",
"\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"file = open('/drive/My Drive/Colab Notebooks/data.txt','r')\n",
"y = file.readlines() # The data is extracted as a list of strings\n",
"print(y)\n",
"#printing the second line only using list indexing operation\n",
"print(y[2])"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "sjVXiNuOcZX6",
"outputId": "81003ed2-8808-4bf8-8ca8-267ed2d888bd"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"['Dear Students\\n', 'This is file handling bhakti\\n', 'We are
learning Text File operations\\n', 'This is really interesting']\n",
"We are learning Text File operations\n",
"\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"file = open('/drive/My Drive/Colab Notebooks/data.txt','r')\n",
"for line in file:\n",
" print(line)\n",
"file.close()"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "_tzeb5PDcfQ6",
"outputId": "cf6524fb-2eb0-4e5b-bcea-b682719ac3d3"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Dear Students\n",
"\n",
"This is file handling bhakti\n",
"\n",
"We are learning Text File operations\n",
"\n",
"This is really interesting\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"\n",
"with open('/drive/My Drive/Colab Notebooks/mystuff.txt','w') as f:\n",
" f.write('Some stuff has been written')\n",
" \n",
"with open('/drive/My Drive/Colab Notebooks/mystuff.txt','r') as f:\n",
" s = f.read()\n",
" print(s)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "w5qYBkNKclde",
"outputId": "98621ddf-28ff-4316-a080-59e890cd673f"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Some stuff has been written\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"file = open('/drive/My Drive/Colab Notebooks/mydata.txt','w')\n",
"file.write('Hancj3$$%GH1234H7')\n",
"file.close()\n",
"file = open('/drive/My Drive/Colab Notebooks/mydata.txt','r')\n",
"res = file.read()\n",
"file.close()\n",
"c1,c2,c3=0,0,0\n",
"for x in res:\n",
" if x.isalpha():\n",
" c1+=1\n",
" elif x.isdigit():\n",
" c2+=1\n",
" else:\n",
" c3+=1\n",
"print(c1,c2,c3)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "GS614NsQcqr4",
"outputId": "73d4d728-6d63-422b-bad4-1f879e1c0f52"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"8 6 3\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"f = open('/drive/My Drive/Colab Notebooks/data.txt','r')\n",
"st = f.read() #It reads the whole content of the file\n",
"print(st)\n",
"f.close()\n",
"c = 0\n",
"for x in st:\n",
" if x.isspace():\n",
" c=c+1\n",
"print('number of words:',c+1)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "gFzS-Cbactjw",
"outputId": "95556de2-33b6-4717-f96b-129ec8584c45"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Dear Students\n",
"This is file handling bhakti\n",
"We are learning Text File operations\n",
"This is really interesting\n",
"number of words: 17\n"
]
}
]
}
],
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

You might also like