Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
suyashi29
GitHub Repository: suyashi29/python-su
Path: blob/master/Python Basics/Errors & ExceptionsDay 5.ipynb
3074 views
Kernel: Python 3
  • 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().

## 1.NameError : passing undefined varaible x
--------------------------------------------------------------------------- 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
## 2. Value Error: Wrong data type Entry1=int(input("Enter a number"))
Enter a number7.8
--------------------------------------------------------------------------- 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'
## 3. Type Error : Wrong operation "abc" * "abc"
--------------------------------------------------------------------------- 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'
## Attribute Error R =(1,2,3) R.append("a")
--------------------------------------------------------------------------- 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'
try: x=int(input("NUMBER1 = ")) y=int(input("NUMBER2 = ")) print(x+y) print(x/y) print(x*y) except Exception #ZeroDivisionError: print("Wrong operation :") finally: print("The 'try except' is finished")
NUMBER1 = 2 NUMBER2 = 0 2 Wrong operation : The 'try except' is finished
try: x=int(input("NUMBER=")) y=int(input("Number")) print(x/y) except Exception as e: print('Caught this error: ' + repr(e)) x=int(input("REenterNUMBER=")) y=int(input("ReenterNumber")) print(x/y)
NUMBER=2.3 Caught this error: ValueError("invalid literal for int() with base 10: '2.3'") REenterNUMBER=3 ReenterNumber0
--------------------------------------------------------------------------- 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
try: x=int(input("Enter First Number=")) y=int(input("Enter Second Number=")) print("sum is:", x+y) print("div is:",x/y) print("product is:",x*y) except Exception as e: if type(e) == ZeroDivisionError: print("oops!!Error wrong divisior") elif type(e)== ValueError: print("Wrong datatype") else: pass
Enter First Number=4 Enter Second Number=0 sum is: 4
try: import times t=time.strftime("%c") print(t) except ImportError as e: print("OOps you have imported wrong module")
OOps you have imported wrong module
try: a=input("Enter file name you want to read") f=open(a,"r") x=f.read() print(x) except IOError as e: print("you have entered wrong file name") a=input("ReEnter file name") f=open(a,"r") x=f.read() print(x)
Enter file name you want to readQ.txt you have entered wrong file name ReEnter file namea1.txt Five lines Happy Five lines Happy

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.

# write a function to create a user name() #assert:len (3-8)
def createusername(uname): assert (len(uname)in range (3,8)) return uname try: a=input("enter user name") print(createusername(a)) except AssertionError as e: print("invalid user name")
enter user name1234567 1234567
def user(name): assert len(name) not in range(3,7) return(name) try: a = input("Enter your name:") print(user(a)) except AssertionError as e: print("invalid length")
Enter your name:abc invalid length
# Without Error message def avg(marks): assert len(marks)!=3 return sum(marks)/len(marks) try: mark2= [1,2,3,4] print("Average of mark1:",avg(mark2)) except AssertionError as e: print("atleast two entry required")
Average of mark1: 2.5
# With error message def avg(marks): assert len(marks) != 0 ,"List is empty." return sum(marks)/len(marks) mark2 = [30,40] print("Average of mark2:",avg(mark2)) mark1 = [] print("Average of mark1:",avg(mark1))

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.

#importing module #importing module import logging #Create and configure logger logging.basicConfig(filename="1.log", format='%(asctime)s %(message)s', filemode='w') #Creating an object logger=logging.getLogger() #Setting the threshold of logger to DEBUG logger.setLevel(logging.DEBUG) #Test messages logger.debug("Harmless debug Message") logger.info("Just an information") logger.warning("Its a Warning") logger.error("Did you try to divide by zero") logger.critical("Internet is down")

Debugging

Python has a debugger, which is available as a module called pdb (for “Python DeBugger”, naturally)

y="ashi"
# epdb1.py -- experiment with the Python debugger, pdb import pdb x=input("Your Name\t") pdb.set_trace() a= "Auto" b = "Desk" c = a + b print (c)

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

x=9 y=10 print(x+y)
def d(x,y=""): print(x,y,sep="\t") d(3,"A") d(-7,"B") d(16,"C")
def is_odd(n): return (n % 2) != 0 list(filter(is_odd, range(20)))
## Same using List Comprephension list(i for i in range(20) if is_odd(i))
s=lambda x,y:(2*x)+y s(3,2)
x=9 eval("x**3+x**2+3")
#Lamda Function : One line functions #lambda argument_list: expression mul = lambda x, y,z : x * y*z mul(3,6,2)

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.

# Return square of n def square(n): return n * n # We double all numbers using map() numbers = (6, -2, 0, 0.4,5) result = map(square, numbers) print(list(result))
2(x*x) n=(-9,11,13)
# Double all numbers using map and lambda numbers =(0, 2 ) result = map(lambda x: x * x, numbers) print(list(result)) #result
L1 = [1, 2, 3,-9] L2 = [4, 5, 6,-6] L1+L2
# Multiplying lists using map and lambda L1 = [1, 2, 3,-9] L2 = [4, 5, 6,-6] result = map(lambda x, y: x / y, L1, L2) print(list(result))
# List of strings l = ['sat', 'fri', 'thru', 'wed'] # map() can listify the list of strings individually test = list(map(list, l)) print(test)
eval("273+44/8-9") #To create output for an quadratic equation.(x3-x2-3x-1),x value user input
round(999.888)
round(999.888,2)
all((1,2,3,4))
all([1,8.8,0,7])
max(False,-4,-1)
min(max(True,4,-1), 3,7)
## WAP to pass a function inside a function def out(a): def inside(b): nonlocal a a += 1 return a+b return inside final= out(2) print(final(2))
# Program to guess a num between range 10 to 20. #Note : User is prompted to enter a guess. If the user guesses wrong then the prompt appears again until the guess is correct, on successful guess, #user will get a "Well guessed!" message, and the program will exit. import random target_num, guess_num = random.randint(9, 21), 12 while target_num != guess_num: guess_num = int(input('Guess a number between 10 and 20 until you get it right : ')) print('Well guessed!')

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.

def factorial(n): print("factorial for n = " + str(n)) if n == 1: return 1 else: res = n * factorial(n-1) print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res) return res print(factorial(5))

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

import os cmd = "git --version" returned_value = os.system(cmd) # returns the exit code in unix print('returned value:', returned_value)
# process path to current working directory import os print ('Starting:', os.getcwd()) print ('Moving up one:', os.pardir) os.chdir(os.pardir) print ('After move:', os.getcwd())
  • 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.

import os print ('popen, read:') pipe_stdout = os.popen('echo "to stdout"', 'r') try: stdout_value = pipe_stdout.read() finally: pipe_stdout.close() print ('\tstdout:', repr(stdout_value)) print ('\npopen, write:') pipe_stdin = os.popen('cat -', 'w') try: pipe_stdin.write('\tstdin: to stdin\n') finally: pipe_stdin.close()
  • 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

import subprocess #cmd = "git --version" returned_value = subprocess.call(cmd, shell=True) # returns the exit code in unix print('returned value:', returned_value)