Python学习(Task9: else与with语句)

mac2026-01-11  7

else与with语句

else

if…else… a = input("请输入:") if int(a) % 2 == 0: print(a + '是一个偶数!') else: print(a + '是一个奇数!') 请输入:5 5是一个奇数! try…except…else… a = input("请输入:") try: int(a) except ValueError as reason: print(str(reason)) else: print('there is no error!') 请输入:1 there is no error! ############################################# a = input("请输入:") try: int(a) except ValueError as reason: print(str(reason)) else: print('there is no error!') 请输入:jh invalid literal for int() with base 10: 'jh'

with

你可以反复调用write()来写入文件,但是务必要调用f.close()来关闭文件。

try: f = open('D:/python/foo1.txt', 'r') print(f.read()) finally: if f: f.close() xdgdf3noob.com! Very good site! www.runoob.com! Very good site! xdgdf

但是with语句更加简洁,再也不用担心文件打开之后忘记close的问题了:

with open('D:/python/foo1.txt', 'r') as f: print(f.read()) xdgdf3noob.com! Very good site! www.runoob.com! Very good site! xdgdf
最新回复(0)