【py code everyday】2023-02-07 second

文章介绍了在Python中如何使用try-except来处理ZeroDivisionError(除零错误)和FileNotFoundError(文件未找到错误)。通过示例代码展示了在执行除法运算和文件读取时,如何优雅地处理可能出现的异常,防止程序崩溃。此外,还提到了split()函数在文本分析中的应用,用于计算文本文件中的单词数量。
摘要由CSDN通过智能技术生成

ZeroDivisionError 异常
0不能被整除

print(5/0)
Traceback (most recent call last):
  File "X:\python_work\test.py", line 1, in <module>
    print(5/0)
ZeroDivisionError: division by zero
[Finished in 71ms]

使用try-except来处理上述的traceback提示

try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")

结果如下

You can't divide by zero!
[Finished in 47ms]

当然了,换成6/0也是这个结论,但如果是结果正常,将跳过except

使用异常避免崩溃

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: ")
    if second_number == 'q':
        break
    answer = int(first_number) / int(second_number)
    print(answer)

输入5/0时,会报错 ZeroDivisionError

First number: 5
Second number: 0
Traceback (most recent call last):
  File "X:\python_work\test.py", line 11, in <module>
    answer = int(first_number) / int(second_number)
ZeroDivisionError: division by zero

Process finished with exit code 1

使用try-except来修正代码

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: ")
    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)
First number: 12
Second number: 0
You can't divide by 0!
First number: q

Process finished with exit code 0

try-except-else的工作原理:
Python尝试执行try代码块中的代码,只有引发异常的代码才需要放在try语句中。
在这里是除以0会引发异常(当然了,其实还有其他会引发异常的情况),把这个除法放在try中
仅在try代码成功执行时才需要执行的代码,这些是需要放在else代码块中
这里是把print(answer)放在else代码块中了
except代码块告诉Python,如果尝试执行了try中的代码时,引发了错误该怎么办

处理 FileNotFoundError 异常

filename = 'alice.txt'
#尝试读取一个不存在的文件
with open(filename,encoding='utf-8') as f: 
    contents = f.read()
Traceback (most recent call last):
  File "X:\python_work\test.py", line 3, in <module>
    with open(filename,encoding='utf-8') as f: 
FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'
[Finished in 62ms]

Python找不到要打开的文件时创建的异常

filename = 'alice.txt'
#尝试读取一个不存在的文件
#通过try-except提示可能引发的FileNotFoundError异常
try:
    with open(filename,encoding='utf-8') as f: 
        contents = f.read()
except FileNotFoundError:
    print(f"Sorry, the file {filename} does not exist.")
Sorry, the file alice.txt does not exist.
[Finished in 62ms]

方法split(),能根据一个字符串创建一个单词列表

title = 'Alice in Wonderland'
print(title.split())
['Alice', 'in', 'Wonderland']
[Finished in 47ms]

分析文本
使用split()来计算.txt的字数多少

filename = 'text_files/alice.txt'

try:
    with open(filename, encoding = 'utf-8') as f:
        contents = f.read()
except FileNotFoundError:
    print(f"Sorry, the file {filename} does not exist.")
else:
    #计算该文件大致包含多少个单词。
    words = contents.split()
    num_words = len(words)
    print(f"The file {filename} has about {num_words} words.")
The file text_files/alice.txt has about 17846 words.
[Finished in 63ms]

使用函数来实现
修改了注释,增加了缩进量

def count_words(filename):
	""" 计算一个文件大致包含多少个单词。"""
    try:
        with open(filename, encoding = 'utf-8') as f:
            contents = f.read()
    except FileNotFoundError:
        print(f"Sorry, the file {filename} does not exist.")
    else:
        words = contents.split()
        num_words = len(words)
        print(f"The file {filename} has about {num_words} words.")
filename = 'text_files/alice.txt'
count_words(filename)

结论

The file text_files/alice.txt has about 17846 words.
[Finished in 63ms]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值