while…else语句
a,b = 0,1 while b < 20: print(b) a,b = b,a+b else: print("this loop is over!")循环语句在结束时添加else语句条件判断为假时运行else语句 for…else语句 for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行 if判断语句中与一个else对应
height = float(input("please input the height:\n")) weight = float(input("please input the weight:\n")) BMI = weight/(height**2) if BMI < 18.5: print("too light") elif 18.5 <= BMI < 25: print("normal") elif 25 <= BMI < 28: print("too heavy") elif 28 <= BMI < 32: print("obesity") else: print("severe obesity") print("the process is over") print(BMI)try …. except … else 语句
如果在 try 子句执行时没有发生异常,Python将执行 else 语句后的语句(如果有 else 的话),然后控制流通过整个 try 语句。
try: a = int(input("Please input an Integer:\n")) r = 10 / a print('result:',r) except ValueError as e: print('ValueError',e) except ZeroDivisionError as e: print('ZeroDivisionError',e) else: print("No error!")关键词 with 语句就可以保证诸如文件之类的对象在使用完之后一定会正确的执行他的清理方法:
with open("myfile.txt") as f: for line in f: print(line, end="")