《Python编程:从入门到实践》异常处理实践

《Python编程:从入门到实践》异常处理实践_第1张图片
《Python编程:从入门到实践》异常处理实践_第2张图片

  • 10-6
try:
    a = input("Enter the first number:")
    b = input("Enter the second number:")
    int(a) + int(b)
except ValueError:
    print("Please enter a number.")
else:
    print(a + " + " + b + " = " + str(int(a) + int(b)))
  • 10-7
while True:
    a = input("Enter the first number (enter q to quit): ")
    if a == "q":
        break
    b = input("Enter the second number:")
    try: 
        int(a) + int(b)
    except ValueError:
        print("Please enter a number.")
    else:
        print(a + " + " + b + " = " + str(int(a) + int(b)))
  • 10-8
try:
    with open('cats.txt') as file_1:
except FileNotFoundError:
    print("cats.txt does not exist")
else:
    file_1_content = file_1.read()
        print(file_1_content)

try:
    with open('dogs.txt') as file_2:
except FileNotFoundError:
    print("dogs.txt does not exist")
else:
    file_2_content = file_2.read()
        print(file_2_content)
  • 10-9
try:
    with open('cats.txt') as file_1:
except FileNotFoundError:
    pass
else:
    file_1_content = file_1.read()
        print(file_1_content)

try:
    with open('dogs.txt') as file_2:
except FileNotFoundError:
    pass
else:
    file_2_content = file_2.read()
        print(file_2_content)

你可能感兴趣的:(《Python编程:从入门到实践》异常处理实践)