Tuesday, May 23, 2023

#PYTHON(DAY27)Exception Handling

 

#PYTHON(DAY27)

Exception Handling

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The else block lets you execute code when there is no error.

The finally block lets you execute code, regardless of the result of the try- and except blocks.

When an error occurs, or exception as we call it, Python will normally stop and generate an error message.

These exceptions can be handled using the try statement:

Example:

The try block will generate an exception, because x is not defined:

try:
print(x)
except:
print("An exception occurred")

And the output is:

An exception occurred

Since the try block raises an error, the except block will be executed.

Without the try block, the program will crash and raise an error:

Example

This statement will raise an error, because x is not defined:

print(x)

And the output is:

Traceback (most recent call last):
File "demo_try_except_error.py", line 3, in <module>
print(x)
NameError: name 'x' is not defined

Many Exceptions

You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error:

Example

Print one message if the try block raises a Name Errorand another for other errors:

try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Variable x is not defined

Else

You can use the else keyword to define a block of code to be executed if no errors were raised:

Example

In this example, the try block does not generate any error:

try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")

And the output is:

Hello
Nothing went wrong

Finally

The finally block, if specified, will be executed regardless if the try block raises an error or not.

Example

try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")

And the output is:

Something went wrong
The 'try except' is finished

Raise an exception

As a Python developer you can choose to throw an exception if a condition occurs.

To throw (or raise) an exception, use the raise keyword.

Example

Raise an error and stop the program if x is lower than 0:

x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")

And the output is:

Traceback (most recent call last):
File "demo_ref_keyword_raise.py", line 4, in <module>
raise Exception("Sorry, no numbers below zero")
Exception: Sorry, no numbers below zero

The raise keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.

Example

Raise a TypeError if x is not an integer:

x = "hello"

if not type(x) is int:
raise TypeError("Only integers are allowed")

And the output is:

Traceback (most recent call last):
File "demo_ref_keyword_raise2.py", line 4, in <module>
raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed

Monday, May 22, 2023

#PYTHON(DAY26)Exception

 

#PYTHON(DAY26)

Exception

What is an Exception?

An exception in Python is an incident that happens while executing a program that causes the regular course of the program’s commands to be disrupted. When a Python code comes across a condition it can’t handle, it raises an exception. An object in Python that describes an error is called an exception.

When a Python code throws an exception, it has two options: handle the exception immediately or stop and quit.

Exception

Exceptions versus Syntax Errors

When the interpreter identifies a statement that has an error, syntax errors occur. Consider the following scenario:

Example:

#Python code after removing the syntax error  
string = "Python Exceptions"

for s in string:
if (s != o:
print( s )

And the output is:

if (s != o:
^
SyntaxError: invalid syntax

The arrow in the output shows where the interpreter encountered a syntactic error. There was one unclosed bracket in this case. Close it and rerun the program:

#Python code after removing the syntax error  
string = "Python Exceptions"

for s in string:
if (s != o):
print( s )

And the output is:

 2 string = "Python Exceptions"
4 for s in string:
----> 5 if (s != o):
6 print( s )

NameError: name 'o' is not defined

We encountered an exception error after executing this code. When syntactically valid Python code produces an error, this is the kind of error that arises. The output’s last line specified the name of the exception error code encountered. Instead of displaying just “exception error”, Python displays information about the sort of exception error that occurred. It was a NameError in this situation. Python includes several built-in exceptions. However, Python offers the facility to construct custom exceptions.

In the next story let’s discuss about Try and Except statements.

Sunday, May 21, 2023

#PYTHON(DAY25)data abstraction

 

#PYTHON(DAY25)

Data Abstraction

It hides the unnecessary code details from the user. Also, when we do not want to give out sensitive parts of our code implementation and this is where data abstraction came.

Data Abstraction in Python can be achieved through creating abstract classes.

abstraction

Why Abstraction is Important?

In Python, an abstraction is used to hide the irrelevant data/class in order to reduce the complexity. It also enhances the application efficiency. Next, we will learn how we can achieve abstraction using python programing.

We use the @abstractmethod decorator to define an abstract method or if we don’t provide the definition to the method, it automatically becomes the abstract method.

Syntax:

from abc import ABC  
class ClassName(ABC):

Example:

# abstract base class work   
from abc import ABC, abstractmethod
class Car(ABC):
def mileage(self):
pass

class Tesla(Car):
def mileage(self):
print("The mileage is 30kmph")
class Suzuki(Car):
def mileage(self):
print("The mileage is 25kmph ")
class Duster(Car):
def mileage(self):
print("The mileage is 24kmph ")

class Renault(Car):
def mileage(self):
print("The mileage is 27kmph ")

# Driver code
t= Tesla ()
t.mileage()

r = Renault()
r.mileage()

s = Suzuki()
s.mileage()
d = Duster()
d.mileage()

And the output is:

The mileage is 30kmph
The mileage is 27kmph
The mileage is 25kmph
The mileage is 24kmph

Friday, May 19, 2023

#PYTHON(DAY24)ENCAPSULATION

 

#PYTHON(DAY24)

Encapsulation

Encapsulation is one of the most fundamental concepts in object-oriented programming (OOP). This is the concept of wrapping data and methods that work with data in one unit. This prevents data modification accidentally by limiting access to variables and methods. An object’s method can change a variable’s value to prevent accidental changes. These variables are called private variables.

encapsulation

Protected Members

Protected members in C++ and Java are members of a class that can only be accessed within the class but cannot be accessed by anyone outside it. This can be done in Python by following the convention and prefixing the name with a single underscore.

The protected variable can be accessed from the class and in the derived classes (it can also be modified in the derived classes), but it is customary to not access it out of the class body.

The __init__ method, which is a constructor, runs when an object of a type is instantiated.

Example:

# Creating a base class
class Base:
def __init__(self):

# Protected member
self._a = 2

# Creating a derived class
class Derived(Base):
def __init__(self):

# Calling constructor of
# Base class
Base.__init__(self)
print("Calling protected member of base class: ",
self._a)

# Modify the protected variable:
self._a = 3
print("Calling modified protected member outside class: ",
self._a)


obj1 = Derived()

obj2 = Base()

# Calling protected member
# Can be accessed but should not be done due to convention
print("Accessing protected member of obj1: ", obj1._a)

# Accessing the protected variable outside
print("Accessing protected member of obj2: ", obj2._a)

And the output is:

Calling protected member of base class:  2
Calling modified protected member outside class: 3
Accessing protected member of obj1: 3
Accessing protected member of obj2: 2

Private members

Private members are similar to protected members, the difference is that the class members declared private should neither be accessed outside the class nor by any base class. In Python, there is no existence of Private instance variables that cannot be accessed except inside a class.

However, to define a private member prefix the member name with double underscore “__”.

class Base1:  
def __init__(self):
self.p = "Javatpoint"
self.__q = "Javatpoint"

# Creating a derived class
class Derived1(Base1):
def __init__(self):

# Calling constructor of
# Base class
Base1.__init__(self)
print("We will call the private member of base class: ")
print(self.__q)


# Driver code
obj_1 = Base1()
print(obj_1.p)

And the output is:

Javatpoint

#PYTHON(DAY23)POLYMORPHISM

 

#PYTHON(DAY23)

Polymorphism

Polymorphism contains two words “poly” and “morphs”. Poly means many, and morph means shape. By polymorphism, we understand that one task can be performed in different ways. For example — you have a class animal, and all animals speak. But they speak differently. Here, the “speak” behavior is polymorphic in a sense and depends on the animal. So, the abstract “animal” concept does not actually “speak”, but specific animals (like dogs and cats) have a concrete implementation of the action “speak”.

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

def info(self):
print(f"I am a cat. My name is {self.name}. I am {self.age} years old.")

def make_sound(self):
print("Meow")


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

def info(self):
print(f"I am a dog. My name is {self.name}. I am {self.age} years old.")

def make_sound(self):
print("Bark")


cat1 = Cat("Kitty", 2.5)
dog1 = Dog("Fluffy", 4)

for animal in (cat1, dog1):
animal.make_sound()
animal.info()
animal.make_sound()

And the output is:

Meow
I am a cat. My name is Kitty. I am 2.5 years old.
Meow
Bark
I am a dog. My name is Fluffy. I am 4 years old.
Bark

Method Overriding

from math import pi


class Shape:
def __init__(self, name):
self.name = name

def area(self):
pass

def fact(self):
return "I am a two-dimensional shape."

def __str__(self):
return self.name


class Square(Shape):
def __init__(self, length):
super().__init__("Square")
self.length = length

def area(self):
return self.length**2

def fact(self):
return "Squares have each angle equal to 90 degrees."

And the output is:

Circle
I am a two-dimensional shape.
Squares have each angle equal to 90 degrees.
153.93804002589985

Building Static Website(part6) HTML Lists

  Building Static Website (part6) HTML Lists Today, let us add some lists to our detailed view section by using html lists. Lists: List is a...