Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
suyashi29
GitHub Repository: suyashi29/python-su
Path: blob/master/Python core/Session2.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().

a=(1,2,3) a.append(3)
try: x=int(input("NUMBER = ")) y=int(input()) print(x+y) print(x/y) print(x*y) except ZeroDivisionError: print("Wrong operation :") finally: print("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))
print("Hi all") name=("Enter your name pls") print("End")
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 either wrong divisior") elif type(e)== ValueError: print("Wrong datatype") else: pass
#ZeroDivisionError #Syntax Error(EOF Error,Indentation Error) #IOError #ImportError #ValueError #NameError #wrong operation :Type ERROR print("*****ZeroDivisionError*******") 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 (ZeroDivisionError,ValueError) as e: print("oops!!Error either wrong division or wrong data type entered") print("ReEnter:") x=int(input("Enter First Number")) y=int(input("Enter Second Number")) print("sum is:", x+y) print("answer is:",x/y) print("product is:",x*y) print("****Module Error*****") try: import time t=time.strftime("%c") print(t) except ImportError as e: print("OOps you have imported wrong module") print("****IOE Error*****") 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) print("Name Error") x=6 try: print("the square of x is",(k*k)) except NameError as e: print("youn have entered unknow variable")

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.

# Without Error message def avg(marks): assert len(marks) != 0 return sum(marks)/len(marks) try: mark2= [] print("Average of mark1:",avg(mark2)) except AssertionError as e: print("Marks cannt be empty")
# 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)
Your Name h --Return-- > <ipython-input-9-f11c12cf4054>(4)<module>()->None -> pdb.set_trace() (Pdb) h Documented commands (type help <topic>): ======================================== EOF c d h list q rv undisplay a cl debug help ll quit s unt alias clear disable ignore longlist r source until args commands display interact n restart step up b condition down j next return tbreak w break cont enable jump p retval u whatis bt continue exit l pp run unalias where Miscellaneous help topics: ========================== exec pdb (Pdb) help Documented commands (type help <topic>): ======================================== EOF c d h list q rv undisplay a cl debug help ll quit s unt alias clear disable ignore longlist r source until args commands display interact n restart step up b condition down j next return tbreak w break cont enable jump p retval u whatis bt continue exit l pp run unalias where Miscellaneous help topics: ========================== exec pdb (Pdb) c AutoDesk

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)
19
def d(x,y=""): print(x,y,sep="\t") d(3,"A") d(-7,"B") d(16,"C")
3 A -7 B 16 C
def is_odd(n): return (n % 2) != 0 list(filter(is_odd, range(20)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
## Same using List Comprephension list(i for i in range(20) if is_odd(i))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
s=lambda x,y:(2*x)+y s(3,2)
8
#Lamda Function : One line functions #lambda argument_list: expression mul = lambda x, y,z : x * y*z mul(3,6,2) mul(3,4,-6)
36 -72

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))
[36, 4, 0, 0.16000000000000003, 25]
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
[0, 4]
L1 = [1, 2, 3,-9] L2 = [4, 5, 6,-6] L1+L2
[1, 2, 3, -9, 4, 5, 6, -6]
# 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))
[0.25, 0.4, 0.5, 1.5]
# List of strings l = ['sat', 'fri', 'thru', 'wed'] # map() can listify the list of strings individually test = list(map(list, l)) print(test)
[['s', 'a', 't'], ['f', 'r', 'i'], ['t', 'h', 'r', 'u'], ['w', 'e', 'd']]
eval("273+44/8-9") #To create output for an quadratic equation.(x3-x2-3x-1),x value user input
269.5

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)