Exception Handling : there are many built in exceptions which are raised in python when something goes wrong.
Exceptions in python can be handled using a key statement. The code that handles the exception is written in the except clause.
Key :
#code [code which might through exception ]
except Excpetion as e:
print (e)
when the exception is handled, the code flow continues without program interruption.
we can also specify the expressions to catch like below :
try :
#code
except ZeroDivision/error :
#code
except TypeError :
#code
except :
#code [all other exceptions are handled here]
Raising Exceptions : we can raise custom exceptions using the raise keyword in python.
try with else clause : sometimes we want to run a piece of code whe try was successful.
try:
#some code
except :
#somr code
else :
#code [this is executed only if the try was successful]
try with finally : python offers a finally clause which ensures execution of a piece of code irrespective of the exception.
try :
# some code
except :
#some code
finally :
#some code [executed regardless of error]
if --name-- == '--main--' in python : --name-- evaluates to the name of the module in python form where the program is run
If the module being run directly from the command line, the --name-- is set to string "--main--" . Thus this behavior is used t check whether the module is run directly or imported to another file.
The global Keyword : global keyword is used to modify the variable outside of the current scope.
enumerate function in python : the enumerate function adds counter to an iterable and returns it
for i, item in list1 :
print(i. item) [prints the items of list1 with index]
List Comprehensions : list comprehension s an elegent way to create list based on existing lists.
list1 = [1,7,12,11,22]
list2 = ;i for item in list1 if item>8]
Programs :
1. #try
while(True):
print("Press q to quit")
a = input("Enter a number: ")
if a == 'q':
break
try:
print("Trying...")
a = int(a)
if a>6:
print("You entered a number greater than 6")
except Exception as e:
print(f"Your input resulted in an error: {e}")
print("Thanks for playing this game")
2. #handling different exception
try:
a = int(input("Enter a number: "))
c = 1/a
print(c)
except ValueError as e:
print("Please Enter a valid value")
except ZeroDivisionError as e:
print("Make sure you are not dividing by 0")
print("Thanks for using this code!")
3. #raising exceptions
def increment(num):
try:
return int(num) + 1
except:
raise ValueError("This is not good - Harry")
a = increment('df364')
print(a)
4. #try with else
try:
i = int(input("Enter a number: "))
c = 1/i
except Exception as e:
print(e)
else:
print("We were successful")
5. #try except finally
try:
i = int(input("Enter a number: "))
c = 1/i
except Exception as e:
print(e)
exit()
finally:
print("We are done")
print("Thanks for using the program")
6. #global
a = 54 # Global variable
def func1():
global a
print(f"Print statement 1: {a}")
a = 8 # Local Variable if global keyword is not used
print(f"Print statement 2: {a}")
func1()
print(f"Print statement 3: {a}")
7. #enumerate
list1 = [3, 53, 2, False, 6.2, "Harry"]
# index = 0
# for item in list1:
# print(item, index)
# index += 1
for index, item in enumerate(list1):
print(item, index)
8. #list comprehension
a = [3, 6, 7, 8, 9, 2, 4, 23, 75, 23, 123, 67]
# b = [ ]
# for item in a:
# if item%2==0:
# b.append(item)
# print(b)
# Shortcut to write the same:
b = [i for i in a if i%2==0]
print(b)
t = [1, 4, 2, 4, 1, 2, 3]
s = {i for i in t}
print(s)