1、else语句
Python中 else 语句不仅可以跟 if 语句进行搭配,还可以跟 for 语句或者 while 语句进行搭配。甚至,else 还能跟异常处理语句进行搭配在与循环进行搭配时,只有在循环顺利完成时,else 中的内容才会执行。如果循环被 break 打断,那么else语句中断内容不会执行下面是求一个数的最大约数的函数,其中 else 语句只有在 while 循环正常退出时(count > 1为假)才会执行,通过break跳出时不会执行for 循环与 else 语句搭配时的用法和这里是一样的 def showMaxFactor(num): count = num // 2 while count > 1: if num % count == 0: print('%d最大的约数是%d' % (num, count)) break count -= 1 else: print('%d是素数' % num) num = int(input('请输入一个数:')) showMaxFactor(num) 和异常处理语句进行搭配,只要try语句中没有出现任何异常,那么就会执行else语句中的内容 try: int('abc') except ValueError as reason: print('出错了:', reason) else: print('没有任何异常')#代码会处理异常ValueError; #将int('abc')修改为int('123')后,则会执行 else 语句的内容 ''' 123 没有任何异常 '''2、with语句
可以主动解决文件未关闭的问题下面代码的问题有:如果以可读的方式打开文件,但是文件不存在,那么 finally 中的 f.close() 是无法执行的 try: f = open('F:\\eric python\\data.txt', 'w') for each in f: print(each) except OSError as reason: print('出错了:', reason) finally: f.close() 使用 with 语句修改如下 try: with open('F:\\eric python\\data.txt', 'w') as f: for each in f: print(each) except OSError as reason: print('出错了:', reason) #这里使用with语句,在文件不被调用时,会自动调用f.close()参考文献
https://www.zybuluo.com/kingwhite/note/128160