Python 7 Levels, L7, Unit 71, Exception

Powered By EmbedPress

Exercise 1:

while True:
    n1 = int(input("Please input first number:"))
    n2 = int(input("Please input second number:"))
    print("{0}/{1}={2}".format(n1,n2,n1/n2))

Exercise 2:

while True:
    n1 = input("Please input first number:")
    n2 = input("Please input second number:")
    if n1.isdigit() and n2.isdigit():
        n1 = int(n1)
        n2 = int(n2)
        if n2 != 0:
            print("{0}/{1}={2}".format(n1,n2,n1/n2))
        else:
            print("Dividend can not be 0")
    else:
        print("Wrong input, non-digit is input.")

Exercise 3:

import traceback
while True:
    try:
        n1 = int(input("Please input first number:"))
        n2 = int(input("Please input second number:"))
        print("{0}/{1}={2}".format(n1,n2,n1/n2))
    except Exception as e:
        print("Exception occurs")
        print(e)
        print(type(e))
        print(repr(e))
        print(traceback.format_exc())

Exercise 4:

import traceback
while True:
    try:
        n1 = int(input("Please input first number:"))
        n2 = int(input("Please input second number:"))
        print("{0}/{1}={2}".format(n1,n2,n1/n2))
    except ValueError:
        print("Wrong input, non-digit is input")
    except ZeroDivisionError:
        print("Dividend can not be 0")
    except BaseException:
        print("Other exeption.")
    else:
        print("No Exception, else statement is executed.")
    finally:
        print("This is executed in spite of exception occurs or not.")

dahan1999

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts