异常
当程序执行错误时,Python 通过异常的特殊对象来管理错误。通常用try-except-else代码块处理异常。
#创建一个除法运算的计算器
print('give me two numbers')
print("enter 'q' to quit. ")
while True:
first_number=input('\nthe first number: ')
if first_number=='q':
break
second_number=input('\nthe second number: ')
if second_number == 'q':
break
answer = int(first_number)/int(second_number)
print(answer)
如上所述的代码块,因为除法部分容易引发错误,比如输入输入除数为 0 的时候引发 ZeroDivisionError 的错误。在可能出错的代码用 try-except-else 来书写。
'''
print('give me two numbers')
print("enter 'q' to quit. ")
while True:
first_number=input('\nthe first number: ')
if first_number=='q':
break
second_number=input('\nthe second number: ')
if second_number == 'q':
break
'''
try:
answer = int(first_number)/int(second_number)
except ZeroDivisionError :
print('you can not divide by 0')
else:
print(answer)
如果 try 中的代码执行成功,那么else代码块会被继续执行。如果出了ZeroDivisionError的错误,那么就执行except下面的代码块。
当然 except 代码块中也可以什么都不做,用 pass 占位。
存储数据
在很多情况下,需要将用户输入的信息存储到文件中。Python 中常用 json 模块来存储数据。
import json
with open('list.json','w') as file:
num=[1,2,3,4]
json.dump(num,file)
with open('list.json') as file:
print(json.load(file))
'''
首先导入json模块,以写入的方式打开该文件。dump函数将内容存储到json文件中。
而load则将文件的内容导读取到内存中。
'''