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]