[Python瀛︿範]Python涓埄鐢╰ry-except澶勭悊浠g爜寮傚父

#-*- coding:gbk -*-

#try-except浠g爜澶勭悊寮傚父

#print(5/0)

#澶勭悊ZeroDivisionError閿欒

try:

聽 聽 print(5/0)

except ZeroDivisionError:

聽 聽 print("You can't divide by zero!")

"""

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("\nSecond number: ")

聽 聽 if second_number == 'q':

聽 聽 聽 聽 break

聽 聽 #answer = int(first_number) / int(second_number)

聽 聽 #print(answer)

聽 聽 #鏀硅壇閿欒

聽 聽 try:

聽 聽 聽 answer = int(first_number) / int(second_number)

聽 聽 except ZeroDivisionError:

聽 聽 聽 聽 print("You can't divide by zero!")

聽 聽 else:

聽 聽 聽 聽 print(answer)

"""

#澶勭悊FileNotFoundError閿欒

#filename = 'alice.txt'

filename = 'filedata/alice.txt'

"""

with open(filename) as file_object:

聽 聽 contents = file_object.read()

聽 聽 print(contents)

"""

try:

聽 聽 with open(filename) as file_object:

聽 聽 聽 聽 contents = file_object.read()

except FileNotFoundError:

聽 聽 #pass

聽 聽 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.")

聽 聽 print("Contents: " + contents)

#灏佽涓轰竴涓嚱鏁帮紝骞跺嚭鐜伴敊璇椂涓嶆彁绀�

def count_words(filename):

聽 聽 try:

聽 聽 聽 聽 with open(filename) as file_object:

聽 聽 聽 聽 聽 聽 contents = file_object.read()

聽 聽 except FileNotFoundError:

聽 聽 聽 聽 pass

聽 聽 else:

聽 聽 聽 聽 words = contents.split()

聽 聽 聽 聽 num_words = len(words)

聽 聽 聽 聽 print("The file " + filename + " has about " + str(num_words) + " words.")

聽 聽 聽 聽 print("Contents: " + contents)

filename = 'filedata/alice.txt'

count_words(filename)

#澶氳绠楀嚑涓枃浠�

filenames = ['filedata/alice.txt', 'filedata/moby_dick.txt', 'filedata/little_women.txt']

for filename in filenames:

聽 聽 count_words(filename)

你可能感兴趣的:([Python瀛︿範]Python涓埄鐢╰ry-except澶勭悊浠g爜寮傚父)