Hello Friends Welcome to GSWSServices GSWS Services Blog Provides you content Regarding GSWS and CSC Services. i am dedicated to provide the updates to you.so,i will keep posting the more important posts on my blog.Please give your support. Thank you for Visiting my Blog.
Assert Statements in Python
1. Simple Version:
assert conditional_expression
2. Augmented Version:
assert conditional_expression, message
conditional_expression will be evaluated and if it is true then the program will be continued.
If it is false then the program will be terminated by raising AssertionError.
By seeing AssertionError, programmer can analyze the code and can fix the problem.
Example
def squareIt(x):
return x * x
assert squareIt(2) == 4, "The square of 2 should be 4"
assert squareIt(3) == 9, "The square of 3 should be 9"
assert squareIt(4) == 16, "The square of 4 should be 16"
print(squareIt(2))
print(Square(3))
print(squareIt(4))
D:\Python3>py test.py
Traceback (most recent call last):
File "test.py", line 4, in <module>
assert squareIt(3) == 9, "The square of 3 should be 9"
AssertionError: The square of 3 should be 9
def squareIt(x):
return x * x
assert squareIt(2) == 4, "The square of 2 should be 4"
assert squareIt(3) == 9, "The square of 3 should be 9"
assert squareIt(4) == 16, "The square of 4 should be 16"
print(squareIt(2))
print(squareIt(3))
print(squareIt(4))
Output
4
9
16
Exception Handling vs Assertions:
Assertions concept can be used to alert programmer to resolve development time errors.
Exception Handling can be used to handle runtime errors.
Debugging Python Program by using assert keyword:
The process of identifying and fixing the bug is called debugging.
Very common way of debugging is to use print() statement. But the problem with the print() statement is, after fixing the bug, compulsorily we have to delete the extra added print() statements, otherwise these will be executed at runtime which creates performance problems and disturbs console output.
To overcome this problem we should go for assert statement. The main advantage of assert statement over print() statement is, after fixing bug we are not required to delete assert statements. Based on our requirement we can enable or disable assert statements.
Hence the main purpose of assertions is to perform debugging. Usually we can perform debugging either in development or in test environments but not in production environment. Hence assertions concept is applicable only for dev and test environments but not for production environment.
Types of assert statements:
There are 2 types of assert statements
Simple Version
Augmented Version
all messages will be written to log file
In the above program only WARNING and higher level messages will be written to log file.
If we set level as DEBUG then all messages will be written to log file.
Copy code
Python
1) import logging
2) logging.basicConfig(filename='log.txt', level=logging.DEBUG)
3) print("Logging Module Demo")
4) logging.debug("This is debug message")
5) logging.info("This is info message")
6) logging.warning("This is warning message")
7) logging.error("This is error message")
8) logging.critical("This is critical message")
log.txt:
Copy code
1) DEBUG:root:This is debug message
2) INFO:root:This is info message
How to implement logging in Python
To perform logging, first we are required to create a file to store messages and we have to specify which level messages we have to store.
We can do this by using basicConfig() function of logging module.
Copy code
Python
logging.basicConfig(filename='log.txt', level=logging.WARNING)
The above line will create a file log.txt and we can store either WARNING level or higher level messages to that file.
After creating log file, we can write messages to that file by using the following methods.
Copy code
Python
logging.debug(message)
logging.info(message)
logging.warning(message)
logging.error(message)
logging.critical(message)
Q. Write a Python program to create a log file and write WARNING and higher level messages?
Copy code
Python
1) import logging
2) logging.basicConfig(filename='log.txt', level=logging.WARNING)
3) print("Logging Module Demo")
4) logging.debug("This is debug message")
5) logging.info("This is info message")
6) logging.warning("This is warning message")
7) logging.error("This is error message")
8) logging.critical("This is critical message")
log.txt:
Copy code
1) WARNING:root:This is warning message
2) ERROR:root:This is error message
3) CRITICAL:root:This is critical message
PYTHON LOGGING
Logging the Exceptions:
It is highly recommended to store complete application flow and exceptions information to a file.
This process is called logging.
The main advantages of logging are:
We can use log files while performing debugging.
We can provide statistics like number of requests per day, etc.
To implement logging, Python provides one inbuilt module called logging.
Logging Levels:
Depending on the type of information, logging data is divided according to the following 6 levels in Python.
CRITICAL ==> 50
Represents a very serious problem that needs high attention.
ERROR ==> 40
Represents a serious error.
WARNING ==> 30
Represents a warning message, some caution needed.
It is an alert to the programmer.
INFO ==> 20
Represents a message with some important information.
DEBUG ==> 10
Represents a message with debugging information.
NOTSET ==> 0
Represents that the level is not set.
Types of Exceptions in Python
-->In Python, there are Two types of exceptions:
1.Predefined Exceptions
2.User Defined Exceptions
1. Predefined Exceptions:
-->Also known as in-built exceptions.
The exceptions which are raised automatically by the Python Virtual Machine whenever a particular event occurs are called predefined exceptions.
Example 1:
Whenever we try to perform division by zero, Python raises ZeroDivisionError.
print(10/0)
Example 2:
Whenever we try to convert input value to int type and the input is not an integer, Python raises ValueError.
x = int("ten") # ValueError
2. User Defined Exceptions:
-->Also known as Customized Exceptions or Programmatic Exceptions.
-->Sometimes we must define and raise exceptions explicitly to indicate that something has gone wrong. Such exceptions are called User Defined Exceptions or Customized Exceptions.
-->The programmer is responsible for defining these exceptions. Python does not know about them, so we must raise them explicitly based on our requirement by using the raise keyword.
Eg:
InsufficientFundsException
InvalidInputException
TooYoungException
TooOldException
-->How to Define and Raise Customized Exceptions:
-->Every exception in Python is a class that extends the Exception class either directly or indirectly.
Syntax:
class classname(predefined exception class name):
def __init__(self, arg):
self.msg = arg
Example:
class TooYoungException(Exception):
def __init__(self, arg):
self.msg = arg
-->TooYoungException is our class name which is the child class of Exception.
-->We can raise an exception by using the
raise keyword as follows:
raise TooYoungException("message")
Complete Example:
class TooYoungException(Exception):
def __init__(self, arg):
self.msg = arg
class TooOldException(Exception):
def __init__(self, arg):
self.msg = arg
age = int(input("Enter Age: "))
if age > 60:
raise TooYoungException("Plz wait some more time you will get best match soon!!!")
elif age < 18:
raise TooOldException("Your age already crossed marriage age... no chance of getting marriage")
else:
print("You will get match details soon by email!!!")
Output:
Enter Age: 12
__main__.TooYoungException: Plz wait some more time you will get best match soon!!!
Copy code
Enter Age: 90
__main__.TooOldException: Your age already crossed marriage age... no chance of getting marriage
Enter Age: 27
You will get match details soon by email!!!
✅Note:👉 raise keyword is best suitable for customized exceptions, but not for predefined exceptions.
Control flow in try–except–finally Python
try:
stmt-1
stmt-2
stmt-3
except:
stmt-4
finally:
stmt-5
stmt-6
Case-1: If there is no exception
1, 2, 3, 5, 6 → Normal Termination
Case-2: If an exception is raised at stmt-2 and the corresponding except block is matched
1, 4, 5, 6 → Normal Termination
Case-3: If an exception is raised at stmt-2 but the corresponding except block is not matched
1, 5 → Abnormal Termination
Case-4: If an exception is raised at stmt-4, then it is always abnormal termination, but before that the finally block will be executed.
Case-5: If an exception is raised at stmt-5 or at stmt-6, then it is always abnormal termination.
Nested try–except–finally blocks:
We can take try–except–finally blocks inside try or except or finally blocks, i.e., nesting of try–except–finally is possible.
try:
--------
--------
--------
try:
--------------
--------------
--------------
except:
--------------
--------------
--------------
--------------
except:
----------
----------
----------
General Rule:
General risky code we have to take inside the outer try block and too much risky code we have to take inside the inner try block.
Inside the inner try block, if an exception is raised, then the inner except block will handle it.
Except block is responsible to handle.
If it is unable to handle, then outer except block is responsible to handle.
Eg:
try:
print("outer try block")
try:
print("Inner try block")
print(10/0)
except ZeroDivisionError:
print("Inner except block")
finally:
print("Inner finally block")
except:
print("outer except block")
finally:
print("outer finally block")
Output
outer try block
Inner try block
Inner except block
Inner finally block
outer finally block
Different Cases in try,except and finally blocks in Python
Case-1: If there is no exception
1) try:
2) print("try")
3) except:
4) print("except")
5) finally:
6) print("finally")
Output
try
finally
Case-2: If there is an exception raised but handled
1) try:
2) print("try")
3) print(10/0)
4) except ZeroDivisionError:
5) print("except")
6) finally:
7) print("finally")
Output
try
except
finally
Case–3: If there is an exception raised but not handled:
1) try:
2) print("try")
3) print(10/0)
4) except NameError:
5) print("except")
6) finally:
7) print("finally")
Output:o
try
finally
ZeroDivisionError: division by zero (Abnormal Termination)
✅Note:There is only one situation where the finally block won’t be executed, i.e., whenever we are using the os._exit(0) function.
==>Whenever we use the os._exit(0) function, the Python Virtual Machine itself is shut down.
==>In this particular case, the finally block won’t be executed.
1) import os
2) try:
3) print("try")
4) os._exit(0)
5) except NameError:
6) print("except")
7) finally:
8) print("finally")
Output:
try
✅Note:os._exit(0)
0 represents the status code
It indicates normal termination
Multiple status codes are possible.
Default except block in Python
-->We can use default except block to handle any type of exceptions.
-->In default except block generally we can print normal error messages.
Syntax:
except:
statements
Example:
try:
x = int(input("Enter First Number: "))
y = int(input("Enter Second Number: "))
print(x / y)
except ZeroDivisionError:
print("ZeroDivisionError: Can't divide with zero")
except:
print("Default Except: Plz provide valid input only")
D:\Python3>py Default.py
Enter First Number: 10
Enter Second Number: 0
ZeroDivisionError: Can't divide with zero
D:\Python3>py Default.py
Enter First Number: 10
Enter Second Number: ten
Default Except: Plz provide valid input only
✅Note:
If try has multiple except blocks, then the default except block should be last.
Otherwise, we will get a SyntaxError.
Example (Wrong Order):
try:
print(10/0)
except:
print("Default Except")
except ZeroDivisionError:
print("ZeroDivisionError")
SyntaxError: default 'except:' must be last
✅Note:
The following are various possible combinations of except blocks:
except ZeroDivisionError:
except ZeroDivisionError as msg:
except (ZeroDivisionError, ValueError):
except (ZeroDivisionError, ValueError) as msg:
except:
finally block:
-->It is not recommended to maintain clean up code (Resource Deallocating Code or Resource Releasing code) inside try block because there is no guarantee for the execution of every statement inside try block always.
-->It is not recommended to maintain clean up code inside except block, because if there is no exception then except block won’t be executed.
Hence we required some place to maintain clean up code which should be executed always irrespective of whether exception raised or not raised and whether exception handled or not handled. Such type of best place is nothing but finally block.
Hence the main purpose of finally block is to maintain clean up code.
try:
Risky Code
except:
Handling Code
finally:
Cleanup code
-->The speciality of finally block is it will be executed always whether exception
raised or not raised and whether exception handled or not handled.
Single except block that can handle multiple exceptions in Python
-->We can write a single except block that can handle multiple different types of exceptions.
except (Exception1, Exception2, Exception3, ...):
or
except (Exception1, Exception2, Exception3, ...) as msg:
Parentheses are mandatory and this group of exceptions is internally considered as a tuple.
Example
try:
x = int(input("Enter First Number: "))
y = int(input("Enter Second Number: "))
print(x / y)
except (ZeroDivisionError, ValueError) as msg:
print("Plz Provide valid numbers only and problem is:", msg)
Output:
D:\Python3>py SingleEx.py
Enter First Number: 10
Enter Second Number: 0
Plz Provide valid numbers only and problem is: division by zero
D:\Python3>py SingleEx.py
Enter First Number: 10
Enter Second Number: ten
Plz Provide valid numbers only and problem is: invalid literal for int() with base 10: 'ten'
How to print exception information in Python
try:
print(10/0)
except ZeroDivisionError as msg:
print("exception raised and its description is:", msg)
Output:
exception raised and its description is: division by zero
try with multiple except blocks:
👉The way of handling exception is varied from exception to exception.
👉Hence,we have to provide separate except block for every exception type.
👉That is, try with multiple except blocks is possible and recommended to use.
Example:
try:
------
------
------
except ZeroDivisionError:
perform alternative arithmetic operations
except FileNotFoundError:
use local file instead of remote file
👉If try with multiple except blocks available, then based on the raised exception, the corresponding except block will be executed.
Example: Multiple except blocks in Python
try:
x = int(input("Enter First Number: "))
y = int(input("Enter Second Number: "))
print(x / y)
except ZeroDivisionError:
print("Can't Divide with Zero")
except ValueError:
print("please provide int value only")
Program Execution:
D:\Python3>py Multi.py
Enter First Number: 10
Enter Second Number: 5
2.0
D:\Python3>py Multi.py
Enter First Number: 10
Enter Second Number: 0
Can't Divide with Zero
D:\Python3>py Multi.py
Enter First Number: 10
Enter Second Number: five
please provide int value only
✅Note: If try has multiple except blocks, the order of the except blocks is important.
👉The Python interpreter always checks from top to bottom and executes the first matching except block.
Example
1) try:
2) x = int(input("Enter First Number: "))
3) y = int(input("Enter Second Number: "))
4) print(x / y)
5) except ArithmeticError:
6) print("ArithmeticError")
7) except ZeroDivisionError:
8) print("ZeroDivisionError")
D:\Python3> py MulEx.py
Enter First Number: 5
Enter Second Number: 0
ArithmeticError
✅Note:
Since ZeroDivisionError is a subclass of ArithmeticError, the except ArithmeticError block will catch it first. That’s why exception order matters in Python.
Control Flow in try–except Python
try:
stmt-1
stmt-2
stmt-3
except XXX:
stmt-4
stmt-5
Case–1:
If there is no exception
1, 2, 3, 5 → Normal Termination
Case–2:
If an exception is raised at stmt-2 and the corresponding except block is matched
1, 4, 5 → Normal Termination
Case–3:
If an exception is raised at stmt-2 and the corresponding except block is not matched
1 → Abnormal Termination
Case–4:
If an exception is raised at stmt-4 or at stmt-5, then it is always abnormal termination.
✅Conclusions:
👉Within the try block, if an exception is raised anywhere, then the rest of the try block will not be executed, even though we handled that exception.
👉Hence, we have to take only risky code inside the try block, and the length of the try block should be as small as possible.
👉In addition to the try block, there may be a chance of raising exceptions inside except and finally blocks also.
👉If any statement which is not part of the try block raises an exception, then it is always abnormal termination.
Customized Exception Handling by using try-except in Python
👉It is highly recommended to handle
exceptions.
👉The code which may raise an exception is
called risky code, and we have to take
risky code inside the try block.
👉The corresponding handling code we
have to take inside the except block.
Syntax:
try:
Risky Code
except XXX:
Handling code / Alternative Code
Example:without try-except:
1. print("stmt-1")
2. print(10/0)
3. print("stmt-3")
Output:
stmt-1
ZeroDivisionError: division by zero
Abnormal termination / Non-Graceful Termination
Example:with try-except:
1. print("stmt-1")
2. try:
3. print(10/0)
4. except ZeroDivisionError:
5. print(10/2)
6. print("stmt-3")
Output:
stmt-1
5.0
stmt-3
Normal termination / Graceful Termination
Python Exception Hierarchy
👉Every Exception in Python is a class.
👉All exception classes are child classes
of BaseException, i.e., every exception
class extends BaseException either
directly or indirectly.
👉Hence, BaseException acts as the root
for the Python Exception Hierarchy.
👉Most of the time, being a programmer,
we have to concentrate on Exception
and its child classes.
Customized Exception Handling by using try-except
👉It is highly recommended to handle
exceptions.
👉The code which may raise an exception is
called risky code, and we have to take
risky code inside the try block.
👉The corresponding handling code we
have to take inside the except block.
Default Exception Handling in Python
👉Every exception in Python is an object.
👉For every exception type, the
corresponding classes are available.
👉Whenever an exception occurs, PVM will create the corresponding exception object and will check for handling code.
👉If handling code is not available, then the Python interpreter terminates the program abnormally and prints corresponding exception information to the console.
👉The rest of the program won’t be executed.
Ex:Python1.py
1) print("Hello")
2) print(10/0)
3) print("Hi")
Output:
D:\Python3>py Python1.py
Hello
Traceback (most recent call last):
File "test.py", line 2, in <module>
print(10/0)
ZeroDivisionError: division by zero
What is Exception in Python?
👉An unwanted and unexpected event
that disturbs normal flow of program
is called exception.
Ex:
ZeroDivisionError
TypeError
ValueError
FileNotFoundError
EOFError
SleepingError
TyrePuncturedError
👉It is highly recommended to handle
exceptions.The main objective of
exception handling is Graceful
Termination of the program.
👉Exception handling does not mean
repairing exception. We have to define
alternative way to continue rest of the
program normally.
Ex:
👉For example our programming
requirement is reading data from remote
file locating at London. At runtime if
London file is not available then the
program should not be terminated
abnormally.
We have to provide local file to continue
rest of the program normally.
This way of defining alternative is nothing
but exception handling.
try:
Copy code
read data from remote file locating at london
exception FileNotFoundError:
use local file and continue rest of the
program normally
Questions
What is an Exception?
What is the purpose of Exception Handling?
What is the meaning of Exception Handling?
Runtime Errors in Python
👉Also known as exceptions.
While executing the program if something goes wrong because of end user input or programming logic or memory problems,then we will get Runtime Errors.
Ex: print(10/0)
==>Zero DivisionError: division by zero
print(10/"ten")
==>TypeError: unsupported operand type(s) for /: 'int' and 'str'
x=int(input("Enter Number:"))
print(x)
D:\Python3>py Excep.py
Enter Number:ten
ValueError: invalid literal for int() with base 10: 'ten'
✅Note: Exception Handling concept applicable for Runtime Errors but not for syntax errors.
Syntax Errors in Python
👉In any programming language there are two types of errors.
1. Syntax Errors
2. Runtime Errors
1. Syntax Errors:
👉The errors which occurs because of invalid syntax are called syntax errors.
Ex: x=10
if x==10
print("Hello")
SyntaxError: invalid syntax
Ex:
print "Hello"
SyntaxError: Missing parentheses in
call to 'print' function.
✅Note:
Programmer is responsible to correct
these syntax errors.Once all syntax errors
corrected then only program execution
will be started.
à°†ంà°§్à°°à°ª్à°°à°¦ేà°¶్à°²ో సదరం సర్à°Ÿిà°«ిà°•ేà°Ÿ్ à°•ోà°¸ం à°Žà°¦ుà°°ుà°šూà°¸్à°¤ుà°¨్à°¨ à°¦ిà°µ్à°¯ాంà°—ులకు à°¸్à°²ాà°Ÿ్ à°¬ుà°•ింà°—్ à°…à°ª్à°¡ేà°Ÿ్.
à°‡ంతకుà°®ుంà°¦ు వరకు SADAREM Slot Booking à°ª్à°°à°•్à°°ిà°¯ à°¸్వర్à°£ à°—్à°°ాà°®ం à°¸్వర్à°£ à°µాà°°్à°¡ు à°¦్à°µాà°°ా à°®ాà°¤్à°°à°®ే à°…ంà°¦ుà°¬ాà°Ÿుà°²ో à°‰ంà°¡ేà°¦ి. à°ª్à°°à°¸్à°¤ుà°¤ం à°ª్రజలకు మరింà°¤ à°¸ౌà°•à°°్యవం...
-
Application Forms for AP Seva Portal Services. 👉CheckSlip For CASTE&Income CheckSlip 👉 Income Application Form Income 👉 Integr...
-
-->The newly developed NBM (Innovation Benefit Management Portal) website has been designed. --To check the eligibility of each scheme....
-
Sadarem Slots booking for month of July, August & September 2023 Starting from 06-07-2023 10:00 am onwards. Slots can be booked at Gr...







