# 循环 # for x in ...循环,依次把list或tuple中的每个元素迭代出来, 把每个元素代入变量x,然后执行缩进块的语句。 # 不要忘了: names = ['Alice','Bob','Tank'] for name in names: print(name) sum = 0 for x in [1,2,3,4,5,6,7,8,9,10]: sum = sum + x print(sum) # rang()函数, 生成一个整数序列 # list()函数可以转化为list print(list(range(5))) sum2 = 0 for x in range(101): sum2 = sum2 + x print(sum2) # while循环,只要满足条件就不断循环 # 计算100以内所有奇数只和 sum3 = 0 n = 99 while n > 0: sum3 = sum3 + n n = n - 2 print(sum3) sum4 = 0 n = 1 while n < 100: sum4 = sum4 + n n = n + 2 print(sum4) # 小练习:请利用循环依次对list中的每个名字打印出Hello, xxx!: L = ['Bart','Lisa','Adam'] for x in L: print('Hello, ' + x + '!') # break 提前退出循环 # n = 1 # while n <= 100: # print(n) # n = n + 1 # print('End') n = 1 while n <= 100: if n > 10: break print(n) n = n + 1 print('END') # continue 跳出这次循环,直接开始下一次循环 # 打印1-20 # n = 0 # while n < 20: # n = n + 1 # print(n) # 打印1-20的奇数 n = 0 while n < 20: n = n + 1 if n % 2 ==0: #如果n是偶数执行continue语句 continue print(n) print('End') # 要特别注意,不要滥用break和continue语句。break和continue会造成代码执行逻辑分叉过多,容易出错。 # 大多数循环并不需要用到break和continue语句. # 打印1-20奇数 n = 1 while n < 20: print(n) n = n + 2 print('END') # 有些时候,如果代码写得有问题,会让程序陷入“死循环”,可以用Ctrl+C退出程序,或者强制结束Python进程。 # n = 2 # while n > 1 : # print(x) # n = n + 1