python異常處理

s=input("enter an integer:")
try:
    i=int(s)
    print("valid integer entered:",i)
except ValueError as err:
        print(err)

while True:
    try:
        x=int(input("Please enter a number:"))
        break
    except  ValueError:
        print("no valid number,try again")

import math
def main():
    print("This program finds the real solution to a quadratic.\n")
    try:
        a,b,c=eval(input("please enter the coefficients(a,b,c):"))
        discRoot=math.sqrt(b*b-4*a*c)
        root1=(-b+discRoot)/(2*a)
        root2=(-b-discRoot)/(2*a)
        print("\nthe solution are:",root1,root2)
    except ValueError as excobj:
        print(excobj)
        if str(excobj)=="math domain error":
            print("no real roots")
        else:
            print("you didn't give me the right numbers")
    except NameError:
        print("\n you didn't enter the three numbers")
    except TypeError:
        print("your inputs were not all numbers")
    except SyntaxError:
        print("you input was not in the correct form")
    except:
        print("something was wrong")
main()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章