1.异常
异常是使用try-except代码块处理的。try-except代码块让Python执行指定的操作,同时告诉Python发生异常时怎么办。
使用了try-except代码块时,即便出现异常,程序也将继续运行:显示你编写的友好错误消息,而不是令用户迷惑的traceback.。
print(5/0)
Traceback (most recent call last): File "exception_division", line 1, in <module> print(5/0) ZeroDivisionError: division by zero
程序奔溃可不好,让用户看到traceback也不是好主意,恶意用户将知道你程序的文件名,还将看到部分不能正确运行的代码。
print("Give me two numbers,and I'll divide them.") print("Enter 'q' to quit.") while True: first_number=input(" First 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)
Give me two numbers,and I'll divide them. Enter 'q' to quit. First number: 5 Second number: 0 You can't divide by 0! First number: 5 Second number: 2 2.5 First number: q
这样,用户看到的是一条友好的错误消息,而不是traceback。
2.存储数据
import json def get_stored_username(): """如果存储了用户名,就获取它""" filename = 'username.json' try: with open(filename) as f_obj: username=json.load(f_obj) except FileNotFoundError: return None else: return username def get_new_username(): """提示用户输入用户名""" username=input("What is your name?") filename = 'username.json' with open(filename,'w') as f_obj: json.dump(username,f_obj) return username def greet_user(): """问候用户,并指出其名字""" username=get_stored_username() if username: print("Welcome back, " + username +"!") else: username=get_new_username() print("We'll remember you when you come back, " + username +"!") greet_user()
第一次运行:
第二次运行: