Task09:else 与 with 语句(1day)

mac2024-05-14  30

Task09:else 与 with 语句(1day) 在前面的循环结构中我们已经涉及到了else语句的使用,在之前的文件管理中我们也涉及到了with语句的使用,下面我们来回顾一下两个语句的使用。 else 1.if else

age=20 if age>=18: print('your age is',age) print('adult') else: print('your age is',age) print('teenager')

2.if elif else

age=20 if age>=6: print('teenager') elif age>=18: print('adult') else: print('kid')

3.while if

n=5 while n>0: print(n) n=n-1 else: print("%d is not more than 0"%n) 5 4 3 2 1 0 is not more than 0

4.try except else

try: print('try...') r=10/int('2') print('result:',r) except ValueError as e: print('ValueError:',e) except ZeroDivisionError as e: print('ZeroDivisionError:',e) else: print('no error!') finally: print('finally...') print('end') try... result: 5.0 no error! finally... end

with 一些对象定义了标准的清理行为,无论系统是否成功的使用了它,一旦不需要它了,那么这个标准的清理行为就会执行。关键词 with 语句就可以保证诸如文件之类的对象在使用完之后一定会正确的执行它的清理方法。

>>> with open('/Users/lenovo/Desktop/text.txt','r') as f: print(f.read()) 123

这段代码执行完毕后,就算在处理过程中出问题了,文件 f 总是会关闭。

最新回复(0)