python基础 while循环 day1
一、while循环:
1、 1+2+..100
i = 1 sum = 0 while i <=100: sum = sum + i i = i + 1 print(sum)
F:\python3.6\python.exe F:/python_workdir/oldboy/while.py 5050
2、while 的跳出循环
方法一:通过break
方法二:通过增加条件
i = 1 while i <=6: print(i) i = i+1
一旦遇到break,就立马跳出循环,不在执行后面的语句
i = 1 while True: print(i) i = i+1 if i >=6: break
3、while之continue:
count=0 while count <=100: count = count + 1 if count > 5 and count < 95: continue print("loop" , count) print("______the end ________") 执行结果: F:\python3.6\python.exe F:/python_workdir/oldboy/while.py loop 1 loop 2 loop 3 loop 4 loop 5 loop 95 loop 96 loop 97 loop 98 loop 99 loop 100 loop 101 ______the end ________
continue的意思是遇到它就立即结束本次循环(不是终止循环),然后开始返回继续下一次的循环,所以当count=6的时候,第一次遇到continue,结束本次循环,后面的语句不在执行,所以没打印,继续下一次的循环
continue就是“见底”
使用while打印1 2 3 4 5 6 8 9 10 (没有7)
count=0 while count <10: count = count + 1 if count == 7: continue else: print(count)
这里的continue也可替换为pass,这也是个关键字,遇到pass什么都不执行