try:
answer =int(first_number)/int(second_number)except ZeroDivisionError:print("You can't divide bu 0!")else:print(answer)
分析文本
filename ='alice.txt'try:withopen(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.")
同时处理多个文件:将需要处理的文件名用列表存储
#定义计算文件有多少个单词的函数defcount_words(filename):try:withopen(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.")
filenames =['alice.txt','siddhartha.txt','moby_dick.txt','little_women.txt']for filename in filenames:
count_words(filename)