i=0
i++
i<3
i=1
i++
i<=3
程序的流程
- 顺序 :从上向下
- 分支:条件判断,决定执行分支
- 循环: 特定代码 重复执行
while循环
例:
i = 1
# 容易忘记写 :
while i <=10:
print("哦嚯")
i=i+1
print("done!")
# 若将i自增注释掉,则变为死循环
赋值运算符
练习0-100求和
# 0-100 求和
result = 0
i=0
while i<=100:
i += 1
result += i
print("结果是%d"%result)
练习0-100偶数求和
# 0-100 偶数 求和
result = 0
i=0
while i<=100:
if i%2 ==0:
result += i
i += 1
print("偶数累加结果是%d"%result)
在循环体内部的关键字
break 和 continue 都只对当下循环有效
break
直接退出循环
i = 0
while i < 10:
print(i)
i += 1
if i == 3:
break
0
1
2
continue
排除某一条件后 继续执行原循环
i = 0
while i<10:
i += 1 # 使用continue 计数器必须修改,否则死循环
# 在这个循环里 i为3 以后立刻跳转到while
if i == 3 :
continue
print(i)
# 如果i自增是在这里的,则代码陷入死循环
1
2
4
5
6
7
8
9
10
循环嵌套
打印小星星
row = 1
while row <= 5:
print("*"*row)
row +=1
*
**
***
****
*****
print 函数默认换行
print("*" , end="")
row = 1
while row <= 5:
col = 1
while col <= row:
print("*",end="")
col += 1
row +=1
***************
row = 1
while row <= 5:
col = 1
while col <= row:
print("*",end="")
col += 1
row +=1
print("") # 每一行结束后换行
乘法表
row = 1
while row <= 9:
col = 1
while col <= row:
print(" %d * %d = %d" % (col , row, col * row),end = "")
col += 1
row += 1
print("")
\t # 垂直对齐
\n # 换行