一、程序的三大流程
在程序开发中,一共有三种流程方式
- 1、顺序:从上到下,顺序执行代码
- 2、分支:根据条件判断,决定执行代码的分支
- 3、循环:让特定代码重复执行
二、while循环—基本语法
i = 0
while i <5:
循环执行的语句 # 循环体执行5次
i = i+1
赋值运算符:赋值运算符中间不能使用空格
c=a+b 将a+b的运算结果赋值给c
c += a 等效于 c = c+a
c -= a 等效于 c = c-a
c *= a 等效于 c = c*a
c /= a 等效于 c = c/a
c //= a 等效于 c = c//a
c %= a 等效于 c = c%a
c **= a 等效于c = c**a
注意:在程序中,除非需求的特殊要求,否则循环的计数都从0开始
三、while循环—练习
# while循环练习——打印5遍“hello python"
i = 0
while i <5:
print("hello python")
i += 1
print("循环结束时,i = %d" % i)
hello python
hello python
hello python
hello python
hello python
循环结束时,i = 5
# 计算0-100之间所有数字的累计求和结果
i = 0
sum = 0
while i <= 100:
sum = sum + i
i += 1
print("0-100之间所有数字的累计求和结果是%d"% sum)
0-100之间所有数字的累计求和结果是5050
# 计算0-100之间所有偶数的累计求和结果
i = 0
sum = 0
while i <= 100:
if i % 2 == 0:
sum += i
i += 1
print("0-100之间所有偶数的累计求和结果是%d"% sum)
0-100之间所有偶数的累计求和结果是2550
四、while循环—break 和continue
break:某一条件满足时,退出循环,不再执行后续重复的代码;
continue:某一条件满足时,结束本次循环,继续下一次循环;
#break 练习
i = 0
while i < 10:
if i == 3:
break
print("hello python")
i += 1
print("over")
hello python
hello python
hello python
over
# continue练习
i = 0
while i < 10:
if i == 3:
i += 1
continue
print(i)
i += 1
0
1
2
4
5
6
7
8
9
五、while循环—嵌套
print()
函数在控制台输出内容后,会自动换行,如果不想换行,可以使用print(" " , end=" ")
字符串中的转义字符:
\t
在控制台输出一个制表符,协助在输出文本时垂直方向保持对齐
\n
在控制台输出一个换行符
\“
在控制台输出双引号“”
# while循环图形练习——圣诞树
shixin=chr(9679)
kongxin = chr(9711)
i = 1
while i <= 5:
print(" " * (5-i),end="")
print("*" * (2*i-1))
i += 1
*
***
*****
*******
*********
# while循环图形练习——正方形
i = 1
while i <= 5:
print(" * " * i + " ^ " * (5 - i))
i +=1
* ^ ^ ^ ^
* * ^ ^ ^
* * * ^ ^
* * * * ^
* * * * *
# while循环图形练习——笑脸
i = 1
while i <= 1:
print("^ " * 2)
print(" "+"^" * i)
i +=1
^ ^
^
# while 循环嵌套打印小星星
row = 1
while row <= 5:
col = 1
while col <= row:
print("*",end="")
col += 1
print("")
row +=1
*
**
***
****
*****
# while 循环嵌套打印_九九乘法表
row = 1
while row <= 9:
col = 1
while col <= row:
print("%d * %d = %d" % (col,row,row * col),end="\t")
col += 1
print("")
row +=1
1 * 1 = 1
1 * 2 = 2 2 * 2 = 4
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16
1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25
1 * 6 = 6 2 * 6 = 12 3 * 6 = 18 4 * 6 = 24 5 * 6 = 30 6 * 6 = 36
1 * 7 = 7 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28 5 * 7 = 35 6 * 7 = 42 7 * 7 = 49
1 * 8 = 8 2 * 8 = 16 3 * 8 = 24 4 * 8 = 32 5 * 8 = 40 6 * 8 = 48 7 * 8 = 56 8 * 8 = 64
1 * 9 = 9 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36 5 * 9 = 45 6 * 9 = 54 7 * 9 = 63 8 * 9 = 72 9 * 9 = 81