Python编程从入门到实践笔记——异常和存储数据

Python编程从入门到实践笔记——异常和存储数据

#coding=gbk
#Python编程从入门到实践笔记——异常和存储数据
#10.3异常
#Python使用被称为异常的特殊对象来管理程序执行期间发生的错误。每当发生让Python不知所措的错误时,它都会创建一个异常对象。
#如果编写了处理该异常的代码,程序将继续运行;如果你未对异常进行处理,程序将停止,并显示一个traceback,其中包含有关异常的报告。
#异常是使用try-except代码块处理的。try-except 代码块让Python执行指定的操作,同时告诉Python发生异常时怎么办。
#使用了try-except代码块时,即便出现异常,程序也将继续运行:显示你编写的友好的错误消息,而不是令用户迷惑的traceback。
 
#1.处理ZeroDivisionError异常
#print(5/0)
 
#2.使用try-except 代码块
try:
    print(5/0)
except ZeroDivisionError:
    print("You can't devide by zero.")
 
 
#3.使用异常避免崩溃
 
#4.else 代码块
#依赖于try 代码块成功执行的代码都应放到else 代码块中:
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 divide by 0!")
    else:
        print(answer)
 
#5.处理FileNotFoundError异常
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)
 
#6.分析文本
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)
else:
    # 计算文件大致包含多少个单词
    words = contents.split()
    num_words = len(words)
    print("The file " + filename + " has about " + str(num_words) + " words.")
 
#7.使用多个文件
def count_words(filename):
    """--snip--"""
    
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
    count_words(filename)
 
#8.失败时一声不吭 pass语句
def count_words(filename):
    """计算一个文件大致包含多少个单词"""
    try:
        """--snip--"""
    except FileNotFoundError:
        pass
    else:
        """--snip--"""
 
 
#10.4存储数据
#1.使用json.dump() 和json.load()
import json
 
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
    json.dump(numbers, f_obj)
 
 
#2.保存和读取用户生成的数据
import json
 
username = input("What is your name? ")
filename = 'username.json'
with open(filename, 'w') as f_obj:
    json.dump(username, f_obj)
    print("We'll remember you when you come back, " + username + "!")
 
with open(filename) as f_obj:
    username = json.load(f_obj)
    print("Welcome back, " + username + "!")

 

你可能感兴趣的:(Python编程从入门到实践笔记——异常和存储数据)