Python 异常

异常

  • python使用被称为异常的特殊对象来管理程序执行期间发生的错误,当有错误发生时,都会创建一个异常对象,将程序继续运行,如果未对异常进行处理,程序将停止,并显示一个traceback,包含有关异常的报告

处理ZeroDivisionError异常

  • 导致Python引发异常的简单错误,例如不能将一个数字除以0
  • ZeroDivisionError异常对象
  • 指出引发了哪种异常,并根据信息对程序进行修改
print(5/0)
---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

<ipython-input-3-fad870a50e27> in <module>()
----> 1 print(5/0)


ZeroDivisionError: division by zero

使用try-except代码块

  • 编写try-except代码来处理可能引发的异常
try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")
You can't divide by zero!

else代码块

  • try代码块只能包含可能导致错误的代码。
  • except代码块告诉Python,出现zerodivisionerror异常时该怎么办,或使用pass语句,使发生异常时一声不吭,直接跳过。
  • else代码块存放try代码块成功执行的代码
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("Second number:")
    try:
        answer = int(first_number) / int(second_number)
    except ZeroDivisionError:
        print("You can't dicide by 0!")
        # pass 直接跳过
    else:
        print(answer)
Give me two numbers,and I'll divide them.
Enter 'q' to quit.

First number:5
Second number:0
You can't dicide by 0!

First number:5
Second number:2
2.5

First number:q

处理FileNotFoundError异常

  • 使用文件时,一种常见的问题是找不到文件:你要查找的文件可能在其他地方、文件名可能不正确或者这个文件根本就不存在。对于所有这些情形,都可使用 try-except 代码块以直观的方式进行处理。
filename = 'alice.txt'
with open(filename) as f_obj:
    contents = f_obj.read()
---------------------------------------------------------------------------

FileNotFoundError                         Traceback (most recent call last)

<ipython-input-11-665c307cd5e9> in <module>()
      1 filename = 'alice.txt'
----> 2 with open(filename) as f_obj:
      3     contents = f_obj.read()


FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'
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.

分析文本

  • 使用方法split(),它根据一个字符串创建一个单词列表
  • 方法 split() 以空格为分隔符将字符串分拆成多个部分,并将这些部分都存储到一个列表中。结果是一个包含字符串中所有单词的列表,虽然有些单词可能包含标点。
>>> title = 'Alice in Wonderland'
>>> title.split()
['Alice', 'in', 'Wonderland']
# coding=gbk
filename = 'alice.txt'

try:
    with open(filename,encoding='UTF-8') as f:
        contents = f.read()
except FileNotFoundError:
    msg = "Sorry, the file " + filename + " does not exist."
    print(msg)
else:
    # 计算文件大致包含多少个单词
    words = contents.split()
    num_words = len(words)
    print("The file " + filename + " has about " + str(num_words) + " words.")
The file alice.txt has about 29465 words.

使用多个文件

  • 将计算文件单词数量放置在一函数里,通过给函数实例化,确定文件名及位置,然后对该文件调用函数,得到计算结果
  • 通过使用for循环来计算多个文件的单词,函数实例化,将文件放置列表中。
  • 为达到显著效果,可以将某些文件放置其他路径下
def count_words(filename):
    try:
        with open(filename,encoding='UTF-8') as f:
            contents = f.read()
    except FileNotFoundError:
        print("Sorry, the file " + filename + " does not exist.")
    else:
        words = contents.split()
        numbers = len(words)
        print("The file " + filename + " has about " + str(numbers) + " words.")

filenames = ['alice.txt','siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
    count_words(filename)
The file alice.txt has about 29465 words.
Sorry, the file siddhartha.txt does not exist.
The file moby_dick.txt has about 215830 words.
The file little_women.txt has about 189079 words.

练习

# 1.加法运算:
# 提示用户停工数值输入时,常出现的一个问题是,用户提供的是文本而不是数字,在这种情况下,
# 当你尝试将输入转换为整数时,将引发TypeError异常,编写一个程序,提示用户输入两个数字,再将它们想加起来并打印结果
# 在用户输入的任何一个值不是数字时都不活TypeError异常,并打印一条友好的错误消息,对编写的程序进行测试:
# 先输入两个数字,在输入一些文本而不是数字。

try:
    x = input("Give me a number: ")
    x = int(x)
    y = input("Give me another number: ")
    y = int(y)
    
except ValueError:
    print("Sorry, I really needed a number.")
else:
    sum = x + y
    print("The sum of " + str(x) + ' and ' + str(y) +' is ' + str(sum) + '.')
    
Give me a number: 23
Give me another number: 4
The sum of 23 and 4 is 27.
# 2.加法计算器:
# 编写的代码放在一个 while 循环中,让用户犯错(输入的是文本而不是数字)后能够继续输入数字。
print("Enter 'q' at any time to quit.\n")
while True:
    try:
        x = input("Give me a number: ")
        if x == 'q':
            break
        x = int(x)
        y = input("Give me antother number: ")
        if x == 'q':
            break
        y = int(y)
        
    except ValueError:
        print("Sorry, I really needed a number.")
    else:
        sum = x + y
        print("The sum of " + str(x) + ' and ' + str(y) + ' is ' + str(sum) + '.')
        
Enter 'q' at any time to quit.

Give me a number: 23
Give me antother number: 47
The sum of 23 and 47 is 70.
Give me a number: 3
Give me antother number: file
Sorry, I really needed a number.
Give me a number: -20
Give me antother number: 20
The sum of -20 and 20 is 0.
Give me a number: q
# 3.猫和狗:
# 创建两个文件 cats.txt 和 dogs.txt ,在第一个文件中至少存储三只猫的名字,在第二个文件中至少存储三条狗的名字。编写一个程序,尝试读取这些文件,
# 并将其内容打印到屏幕上。将这些代码放在一个 try-except 代码块中,以便在文件不存在时捕获 FileNotFound 错误,并打印一条友好的消息。将其中一个文件
# 移到另一个地方,并确认 except 代码块中的代码将正确地执行。
# cat.txt
xiao hua
hu zi
hua zai
# dog.txt
lao da
lao er
lao san 
# cat_and_dog.py
def cat_and_dog(filename):
    try :
        with open(filename,'r') as f:
            notes = f.read()

    except FileNotFoundError:
        print("Sorry, The file is not exict.")
    else:
        print(notes + '\n')

filenames = ['cat.txt','dog.txt']
for filename in filenames:
    cat_and_dog(filename)

运行:
在这里插入图片描述

移出cat.txt
在这里插入图片描述

# 4.沉默的猫和狗
# 修改你在练习3中编写的 except 代码块,让程序在文件不存在时一言不发。使用pass
# cat_and_dog.py
def cat_and_dog(filename):
    try :
        with open(filename,'r') as f:
            notes = f.read()

    except FileNotFoundError:
        pass     
    else:
        print(notes + '\n')

filenames = ['cat.txt','dog.txt']
for filename in filenames:
    cat_and_dog(filename)

运行:
在这里插入图片描述

# 5.常见单词:
# 针对文本可以使用方法 count() 来确定特定的单词或短语在字符串中出现了多少次。
# 例如,下面的代码计算 'row' 在一个字符串中出现了多少次:
line = "ROw ,row,row your boat"
line.count('row')
2

通过使用 lower() 将字符串转换为小写,可捕捉要查找的单词出现的所有次数,而不管其大小写格式如何。

line.lower().count('row')
3
posted @ 2022-11-30 09:10  野哥李  阅读(11)  评论(0编辑  收藏  举报  来源