Path: blob/master/Python Basics/Errors & ExceptionsDay 5.ipynb
3074 views
Errrors
Exceptions
Debugging
Functional Programming
Exceptions
Exception Classes classes
The following exceptions are used mostly as base classes for other exceptions.
exception BaseException The base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes (for that, use Exception). If str() is called on an instance of this class, the representation of the argument(s) to the instance are returned, or the empty string when there were no arguments.
args The tuple of arguments given to the exception constructor. Some built-in exceptions (like OSError) expect a certain number of arguments and assign a special meaning to the elements of this tuple, while others are usually called only with a single string giving an error message.
with_traceback(tb) This method sets tb as the new traceback for the exception and returns the exception object. It is usually used in exception handling code.
exception Exception
All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class.
exception ArithmeticError
The base class for those built-in exceptions that are raised for various arithmetic errors: OverflowError, ZeroDivisionError, FloatingPointError.
exception BufferError
Raised when a buffer related operation cannot be performed.
exception LookupError
The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid: IndexError, KeyError. This can be raised directly by codecs.lookup().
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-7-788a2990bdfa> in <module>
1 ## 1.NameError : passing undefined varaible
2
----> 3 x
NameError: name 'x' is not defined
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-8-d4290a8e2585> in <module>
1 ## 2. Value Error: Wrong data type
----> 2 Entry1=int(input("Enter a number"))
ValueError: invalid literal for int() with base 10: '7.8'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-32bc00c020aa> in <module>
1 ## 3. Type Error : Wrong operation
----> 2 "abc" * "abc"
TypeError: can't multiply sequence by non-int of type 'str'
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-10-ce18c7557c01> in <module>
1 ## Attribute Error
2 R =(1,2,3)
----> 3 R.append("a")
AttributeError: 'tuple' object has no attribute 'append'
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-17-22ec250599ec> in <module>
1 try:
----> 2 x=int(input("NUMBER="))
3 y=int(input("Number"))
ValueError: invalid literal for int() with base 10: '2.3'
During handling of the above exception, another exception occurred:
ZeroDivisionError Traceback (most recent call last)
<ipython-input-17-22ec250599ec> in <module>
8 x=int(input("REenterNUMBER="))
9 y=int(input("ReenterNumber"))
---> 10 print(x/y)
11
12
ZeroDivisionError: division by zero
Concrete exceptions¶
The following exceptions are the exceptions that are usually raised.
exception AssertionError Raised when an assert statement fails.
exception AttributeError Raised when an attribute reference (see Attribute references) or assignment fails. (When an object does not support attribute references or attribute assignments at all, TypeError is raised.)
exception EOFError Raised when the input() function hits an end-of-file condition (EOF) without reading any data. (N.B.: the io.IOBase.read() and io.IOBase.readline() methods return an empty string when they hit EOF.)
exception FloatingPointError Not currently used.
exception GeneratorExit Raised when a generator or coroutine is closed; see generator.close() and coroutine.close(). It directly inherits from BaseException instead of Exception since it is technically not an error.
exception ImportError Raised when the import statement has troubles trying to load a module. Also raised when the “from list” in from ... import has a name that cannot be found.
What is Assertion?
Assertions are statements that assert or state a fact confidently in your program. For example, while writing a division function, you're confident the divisor shouldn't be zero, you assert divisor is not equal to zero.
Assertions are simply boolean expressions that checks if the conditions return true or not. If it is true, the program does nothing and move to the next line of code. However, if it's false, the program stops and throws an error
Python's assert statement is a debugging aid that tests a condition. If the condition is true, it does nothing and your program just continues to execute. But if the assert condition evaluates to false, it raises an AssertionError exception with an optional error message.
Python assert Statement
Python has built-in assert statement to use assertion condition in the program. assert statement has a condition or expression which is supposed to be always true. If the condition is false assert halts the program and gives an AssertionError.
Log Generation
Logging is a means of tracking events that happen when some software runs. Logging is important for software developing, debugging and running. If you don’t have any logging record and your program crashes, there are very little chances that you detect the cause of the problem.
There are two built-in levels of the log message.
Debug : These are used to give Detailed information, typically of interest only when diagnosing problems.
Info : These are used to Confirm that things are working as expected
Warning : These are used an indication that something unexpected happened, or indicative of some problem in the near future
Error : This tells that due to a more serious problem, the software has not been able to perform some function
Critical : This tells serious error, indicating that the program itself may be unable to continue running
Logging module is packed with several features. It has several constants, classes, and methods. The items with all caps are constant, the capitalize items are classes and the items which start with lowercase letters are methods. There are several logger objects offered by the module itself.
Logger.info(msg) : This will log a message with level INFO on this logger.
Logger.warning(msg) : This will log a message with level WARNING on this logger.
Logger.error(msg) : This will log a message with level ERROR on this logger.
Logger.critical(msg) : This will log a message with level CRITICAL on this logger.
Logger.log(lvl,msg) : This will Logs a message with integer level lvl on this logger.
Logger.exception(msg) : This will log a message with level ERROR on this logger.
Logger.setLevel(lvl) : This function sets the threshold of this logger to lvl. This means that all the messages below this level will be ignored.
Logger.addFilter(filt) : This adds a specific filter filt to the to this logger.
Logger.removeFilter(filt) : This removes a specific filter filt to the to this logger.
Debugging
Python has a debugger, which is available as a module called pdb (for “Python DeBugger”, naturally)
Functional Programming
Functional programming is a programming paradigm, a style of building the structure and elements of computer programs, that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.
In simple words Functional programming focus on task.
Outlines for functional programming
Pure functions
Ways and constructs to limit the use of for loops
Good support for recursion
Functions as first class objects in python
Map : map() function returns a list of the results after applying the given function to each item of a given iterable.
map(fun, iter) : Syntax
fun : It is a function to which map passes each element of given iterable.
iter : It is a iterable which is to be mapped.
NOTE : You can pass one or more iterable to the map() function.
Python Recursion:
Recursion is a method of breaking a problem into subproblems which are essentially of the same type as the original problem. You solve the base problems and then combine the results. Usually this involves the function calling itself.A recursive function has to fulfil an important condition to be used in a program: it has to terminate. A recursive function terminates, if with every recursive call the solution of the problem is downsized and moves towards a base case.
Process management and process automation (3hrs)¶
Python subprocess.check_output() function
Using subprocess.check_output() function we can store the output in a variable.
Using os.system, os.popen, os.fork, os.exec functions
Using the commands module
Using the subprocess module
Managing processes using various functions in os module
popen():It creates a new process running the command given and attaches a single stream to the input or output of that process, depending on the mode argument. While popen() functions work on Windows, some of these examples assume a Unix-like shell.
stdin - The “standard input” stream for a process (file descriptor 0) is readable by the process. This is usually where terminal input goes.
stdout - The “standard output” stream for a process (file descriptor 1) is writable by the process, and is used for displaying regular output to the user.
stderr - The “standard error” stream for a process (file descriptor 2) is writable by the process, and is used for conveying error messages.
The subprocess module present in Python(both 2.x and 3.x) is used to run new applications or programs through Python code by creating new processes.
The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions