You are on page 1of 6

# Python program to display all the prime numbers within an interval

lower = 900
upper = 1000

print("Prime numbers between", lower, "and", upper, "are:")

for num in range(lower, upper + 1):


# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)

#Python Program to Find the Factors of a Number


x=int(input("enter the no. to find the factors of a number")
for i in range(1, x + 1):
if x % i == 0:
print(i)

#How to Check if a Python String is a Palindrome


#Enter input string
string = input("Enter string : ")
 
#Declare an empty string variable 
revstr = ""
 
#Iterate string with for loop
for i in string:
    revstr = i + revstr  
print("Reversed string : ", revstr)
 
if(string == revstr):
   print("The string is a palindrome.")
else:
   print("The string is not a palindrome.")

Python Pass Statement


The pass statement is used as a placeholder for future code. When the pass statement is executed, nothing happens,
but you avoid getting an error when empty code is not allowed. Empty code is not allowed in loops, function
definitions, class definitions, or in if statements. The pass statement is a null statement. But the difference between
pass & comment is that comment is ignored by the interpreter whereas pass is not ignored. It is interpreted as a
placeholder for the future execution of functions, classes, loops, etc.
When the user does not know what code to write, So user simply places pass at that line. Sometimes, pass is
used when the user doesn’t want any code to execute. So user can simply place pass where empty code is not
allowed, like in loops, function definitions, class definitions, or in if statements. So using pass statement user
avoids this error.
#lets take another example in which the pass statement get executed when the condition is true

# Python program to demonstrate for-else loop without print statement


#and it will show error
for i in range(1, 4):
#print(i) # do't write it
pass
else: # Executed because no break in for
print("No Break\n")

# The pass is also useful in places where your code will eventually go, but has not been written
yet : for example) −
for letter in 'Python':
if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter

print "Good bye!"

Python Exception Handling


Error in Python can be of two types i.e. Syntax errors and Exceptions. 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.

Exception Handling in is one of the effective means to handle the runtime errors so that the
regular flow of the application can be preserved. Python Exception Handling is a mechanism to handle
runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Exception is an unwanted or unexpected event, which occurs during the execution of a program,
i.e. at run time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught
and handled by the program. When an exception occurs within a method, it creates an object. This
object is called the exception object. It contains information about the exception, such as the name
and description of the exception and the state of the program when the exception occurred.

There are two types of errors:


1. Compile time errors
2. Runtime errors
3. Syntax Errors

For handling exceptions, there are 2 possible approaches


1. PVM
If an exception is not handled explicitly, then PVM takes the responsibility of handling
the exception.
Once the exception is handled, PVM will halt the program and no more execution of
code will take place
2. Developer
Developers can explicitly write the implementation for handling the exception. Once an
exception is handled, the normal execution of code will continue.Preferable: handle
exceptions to ensure your code gets executed normally.

Major reasons why an exception Occurs


 Invalid user input
 Device failure
 Loss of network connection
 Physical limitations (out of disk memory)
 Code errors
 Opening an unavailable file

Advantage of Exception Handling: The core advantage of exception handling is to maintain
the normal flow of the application. An exception normally disrupts the normal flow of the
application; that is why we need to handle exceptions. 

Errors represent irrecoverable conditions such as Python virtual machine (JVM)


running out of memory, memory leaks, stack overflow errors, library incompatibility,
infinite recursion, etc. Errors are usually beyond the control of the programmer, and
we should not try to handle errors. Let us discuss the most important part which is
the differences between Error and Exception that is as follows: 
 Error: An Error indicates a serious problem that a reasonable application
should not try to catch.
 Exception: Exception indicates conditions that a reasonable application
might try to catch.

To understand the exception firstly we should know about the error in program. Errors in program can
be categorized into two types.
 Compile Time Errors
 Run Time Errors
 Syntax Errors
 Logical Errors
Compile Time Errors:- Errors caught during compiled time is called Compile time errors. Compile
time errors include library reference, syntax error or incorrect class import.
Run Time Errors:- The error that occurs during the run time of program is called run time error.
Syntax Error: Errors are the problems in a program due to which the program will stop the
execution
Logical Errors: :- The error that occurs during the logics which are interpret in the program.

They are also known as exceptions. Hence we can say that exception is a runtime error that occurs
because of user's mistake.

Reasons of Exception
Mismatched Input :Suppose that we are entering our name in place of age,causing exception
because age is of data type int and name will be string. 
File does not exist :Suppose that we are reading a text file easy.txt and that file does not
exist in the system, causing exception.
Divide by zero exception :When a number is divided by zero then the output will be
undefined(infinity).
IndentationError: If incorrect indentation is given.
Addition of two incompatible types
Trying to access a nonexistent index of a sequence
Removing the table from the disconnected database server.
ATM withdrawal of more than the available amount
Error vs. Exceptions
Error Exceptions
All errors in Python are the unchecked type. Exceptions include both checked and unchecked
type.
Errors occur at run time which unknown to the Exceptions can be recover by handling them with
compiler. the help of try-catch blocks.
Errors are mostly caused by the environment in The application itself causes exceptions.
which an application is running.
Examples: Examples:
OutofMemoryError Checked Exceptions, SQL exception,
NullPointerException,etc.

Important Python Errors


Error Type Description
ArithmeticError ArithmeticError act as a base class for all arithmetic exceptions. It is raised for
errors in arithmetic operations.
ImportError ImportError is raised when you are trying to import a module which does not
present. This kind of exception occurs if you have made typing mistake in the
module name or the module which is not present in the standard path.
IndexError An IndexErroris raised when you try to refer a sequence which is out of range.
KeyError When a specific key is not found in a dictionary, a KeyError exception is raised.
NameError A NameError is raised when a name is referred to in code which never exists in
the local or global namespace.
ValueError Value error is raised when a function or built-in operation receives an argument
which may be of correct type but does not have suitable value.
EOFerror This kind of error raises when one of the built-in functions (input() or
raw_input()) reaches an EOF condition without reading any data.
ZeroDivisonError This type of error raised when division or module by zero takes place for all
numeric types.
IOError- This kind of error raised when an input/output operation fails.
syntaxError SyntaxErrors raised when there is an error in Python syntax.
IndentationError This error raised when indentation is not properly defined

Other Important Python Exceptions


Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArraylndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment helps you to the array element of an incompatible
type.
ClassCastException Invalid cast
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object which does not implement the
Cloneable interface.
Illegal AccessException Access to a class is denied.

Syntax of try _ except _ else _ finally

try:
#block of statements
except:
#block of statements
else:
#block of statements
finally:
#block of statements

How will it work? Syntax:


try:
#run this code
except:
#this code will run
#if exception occurs
else:
#this code will run
#if no exception occurs
finally:
#this code will always run

Why should you use Exceptions?


 Exception handling allows you to separate error-handling code from normal code.
 An exception is a Python object which represents an error.
 As with code comments, exceptions helps you to remind yourself of what the program
expects.
 It clarifies the code and enhances readability.
 Allows you to stimulate consequences as the error-handling takes place at one place and in
one manner.
 An exception is a convenient method for handling error messages.
 In Python, you can raise an exception in the program by using the raise exception method.
 Raising an exception helps you to break the current code execution and returns the exception
back to expection until it is handled.
 Processing exceptions for components which can’t handle them directly.

#Example:
# initialize the amount variable
marks = 67
# perform division with 0
a = marks / 0
print(a)

a = int(input(" Please Enter any no for division: "))


b = int(input(" Please Enter any divisor: "))
c=a/b
print("the op/ is = " ,c)
print("the op/ is mandatory = ")

#Example Complete
try:
a = int(input(" Please Enter any no for division: "))
b = int(input(" Please Enter any divisor: "))
c=a/b
except ValueError as v:
print("sum does not exist and ", v)
except ZeroDivisionError as e:
print("Cannot divide by 0 and ",e)
except:
print("Something went wrong")

else:
print("else block")
print("the op/ is = " ,c)

finally:
print("Mandatory Block ")
print(" I AM ALWAYS WITH YOU!!!!!!")

You might also like