🐍 Below are some of the examples to display use of Try, Except, Else, Finally
for i in ['a','b','c']:
print(i**2)
except TypeError:
print("Inside except. One or more of the list elements are not of type integer.")
y = 0
try:
z = x/y
except ZeroDivisionError:
print("Inside Except. Denomibator cannot be 0 to execute division. Please update the denominator.")
finally:
print("Inside finally.")
Example — Try, Except
try:for i in ['a','b','c']:
print(i**2)
except TypeError:
print("Inside except. One or more of the list elements are not of type integer.")
Example — Try, Except, Finally
x = 5y = 0
try:
z = x/y
except ZeroDivisionError:
print("Inside Except. Denomibator cannot be 0 to execute division. Please update the denominator.")
finally:
print("Inside finally.")
Example — Try, Except, Else
def ask():
while True:
try:
result=int(input("Enter an integer to square:"))
except ValueError:
print("Inside except. That is not an integer. Try again.")
continue
else:
print(f"Sqaure of {result} is {result**2}")
break
ask()
Comments
Post a Comment