if…else语句
if 条件为真: 执行命令1 else: 执行命令2while…else 语句
a=0 while a>5: print(a,'是大于5的数') a-=1 else: print(a,'是小于或等于5的数') #10 是大于5的数 #9 是大于5的数 #8 是大于5的数 #7 是大于5的数 #6 是大于5的数 #5 是小于或等于5的数for…else for语句用法和普通的用法相同
a=1 for i in range(1,6): a=a*i else: print('5的阶乘=',a) #5的阶乘= 120try…except…else 语句 try…except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理。 如果你不想在异常发生时结束你的程序,只需在try里捕获它。
try: int('abc') except ValueError as reason: print('出错了'+str'reason') else: print('没有出错') #出错了invalid literal for int() with base 10: 'abc'使用with后不管with中的代码出现什么错误,都会进行对当前对象进行清理工作
try: f=open('data.txt','w')#data文件并不存在 for each_line in f: print(each_line) except OSError as reason: print('出错了:',+str(reason)) finally: f.close #出错了: not readable