There are many built in exceptions which are raised in python when something goes wrong. Exceptions in python can be handled using a try statement. The code that handles the exception is written in the except clause.
try:
#code
except Exception as e:
print(e)
when the exception is handled the code flow continues without program interruption.
try:
#code
except ZeroDivisionError:
#code
except TypeError:
#code
except:
#code
Raising Exceptions:
We can raise custom exceptions using the raise keuword.
try with else clause:
sometimes we want to run a piece of code when try was successful.
try:
#code
except:
#code
else:
#code
try with finally:
python offers a finally clause which ensures execution of a piece of code irrespective of the exception.
try:
#code
except:
#code
finally:
#code
if __name__ = '__main__':
__name__ evaluates to the name of the module in python from where the program is run. if the module is being run directly from the cmd line the __name__ is set to string "__main__".
thus this behaviour is used to check if the module is run directly or imported to another file.
Global keyword:
global keyword is used to modify the variable outside of the current scope.
enumerate function:
It adds counter to an iterable and returns it.
for i,item in enumerate(list1):
print(i,item)
list comprehensions:
It is an elegant way to create lists based on existing lists.
list1=[1,7,12,11,22]
list2=[i for item in list1 if item >8]
Practice:
Write a program to open 3 files 1.txt,2.txt and 3.txt.if any one of the files do not present then a message without exiting the program must be printed prompting the same.
WAP to print 3rd,5th and 7th element from a list using enumerate function.
Write a list comprehension to print a list which contains the multiplication table of a user entered number.
WAP to display a/b where a and b are integers. if b=0, display infinite by handling the ZeroDivisionError.
No comments:
Post a Comment