循环——while语句
语法
block 块(代码块)
while condition:
block
当条件满足condition位True,进入循环体,执行block
举例
flag = 10
while flag:
print(flag)
flag -= 1
循环——for语句
语法
element 元素
iterable 可迭代对象
for element in iterable:
block
当可迭代对象中有元素可以迭代,进入循环体,执行block
range函数
一般当做计数器用
range(start, stop[, step])
help(range) # 可以查看python提供的帮助文件
range? #可以查看ipython提供的帮助文件
帮助文件里面的 [ ] 表示可以省略不写
举例:打印1~10
for i in range(10): # i从range内取一个元素赋值
print(i+1)
range(10) => [0,10)
循环continue语句
- 中断当前循环的当次执行,继续下一次循环
- 举例:计算10以内的偶数(for循环)
for i in range(10):
if not i % 2:
print(i)
用continue语句实现
for i in range(10):
if i % 2:
continue
print(i)
循环break语句
- 终止当前循环
- 举例:计算1000以内的正整数被7整除的前20个数(for循环)
例子一:
例子二count = 0 for i in range(7,1000): if not i % 7: print(i) coount += 1 if count == 20: break
count = 1 for i in range (7,1000,7): print(i) if count == 20: break count += 1
循环continue、break语句
- 总结
- continue和break是循环的控制语句,之影响当前循环,包括while、for循环
- 如果循环嵌套,continue和break也只影响语句所在的那一层
- continue和break不是跳出语句块,所以if cond:break 不是跳出if,而是终止if外的break所在的循环
练习:
- 给定一个不超过5位数的正整数,判断该数的位数,依次打印出万位、千位、百位、十位、个位的数字
分析
示例一
示例二number = "54321" number = int(number) weight = 10000 while number: print(number // weight) number = number % weight weight = weight // 10
number = int("54321") weight = 10000 for i in range(5): print(number//weight) number %= weight # =>number = number % weight weight //=10 # => weight = weight % 10
练习
- 给定一个不超过5位的正整数,判断该数的位数,依次从万位打印到个位的数字
示例number = int("02100") weight = 10000 count = 0 button = False for i in range(5): t = number // weight if t: button = True if button: print(number//weight) count += 1 number %= weight # =>number = number % weight weight //=10 # => weight = weight % 10 print("count:",count)
练习
- 给定一个不超过5位数的正整数,判断该数的位数,依次打印出个位、十位、百位、千位、万位的数字
示例一
示例二number = int("32100") if number > 1000: if number > 10000: # print(5) c = 5 else: # print(4) c = 4 else : if number > 100: # print(3) c = 3 elif number >10: # print(2) c = 2 else : # print(1) c = 1 for i in range(c): n = number //10 print(number - n*10) number //= 10 print("count:",c)
number = int("32100") if number > 1000: if number > 10000: # print(5) c = 5 else: # print(4) c = 4 else : if number > 100: # print(3) c = 3 elif number >10: # print(2) c = 2 else : # print(1) c = 1 for i in range(c): print(number % 10) number //= 10 print("count:",c)
循环 else子句
- 语法
while condition: block else: block
for element in iterable: block else: block
- 如果循环正常执行结束,就执行else子句,即使循环没有进去
- 如果使用break终止,else子句不会执行
Tips:
- pass 表示空语句
- 循环使用要注意边界控制
- Jupyter notebook
点In [ ] 按L键可以显示行号 - 减少循环次数可以有效提高程序效率