美文网首页python
try-except-else

try-except-else

作者: 庵下桃花仙 | 来源:发表于2018-11-23 22:09 被阅读1次
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")

while True:
    first_number = input("\nFirst number: ")
    if first_number == 'q':
        break
    second_number = input("\nSeconf number: ")
    if second_number == 'q':
        break
    try:
        answer = int(first_number) / int(second_number)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(answer)
Give me two numbers, and I'll divide them.
Enter 'q' to quit.

First number: 5 

Seconf number: 3
1.6666666666666667

First number: 5

Seconf number: 0
You can't divide by 0!
filename = 'alice.txt'

try:
    with open(filename) as f_obj:
        contents = f_obj.read()
except FileNotFoundError:
    msg = "Sorry, the file " + filename + " does not exist."
    print(msg)
Sorry, the file alice.txt does not exist.

相关文章

网友评论

    本文标题:try-except-else

    本文链接:https://www.haomeiwen.com/subject/dabsqqtx.html