循环语句
一、while 循环
while 语法
while 条件:
条件满足时,做事情
python
a = 0
while a < 100:
print('i like python ...')
a += 1
求 1-100 的总和
python
i = 1
sum = 0
while i <= 100:
sum += i
i += 1
print(f'1-100 的和是 {sum}')
"""
1-100 的和是 5050
"""
while 嵌套循环
while 条件1:
条件满足时,做事情1
while 条件2:
条件满足时,做事情2
嵌套案例1:表白
表白 100 天,每天送 10 支花
python
i = 1
while i <= 100:
print(f'i love python, 表白的第{i}天')
j = 1
while j <= 10:
print(f'\t送你第{j}支花')
j += 1
i += 1
嵌套案例2:99乘法表
python
i = 1
while i <= 9:
j = 1
while j <= i:
print(f'{j} * {i} = {i * j}', end='\t')
j += 1
print()
i += 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
"""
二、for 循环
for 语法:
for 临时变量 in 待处理的数据集:
循环满足条件的表达式
python
str_ = 'hello world'
for s in str_:
print(s, end=' ')
"""
h e l l o w o r l d
"""
python 中 for 循环是无法构建死循环的
练习题
数一数 'a' 一共出现了几次
python
line_ = 'itheima is a brand of itcast'
a = 0
for i in line_:
if i == 'a':
a += 1
print(f'a 字符一共出现了{a}次')
"""
a 字符一共出现了4次
"""
range 语句
range 三种写法
方法一:
range(num)
获取一个从 0 开始,到 num 结束的数字序列(不含 num 本身)
如:range(5) 结果:【0,1,2,3,4】
方法二:
range(num1, num2)
获取从 num1 开始,到 num2 的数字学列且不含 num2 本身
如:range(5, 10) 结果:【5,6,7,8,9】
方法三:
range(num1, num2,setp)
获取从 num1 开始,到 num2 的数字学列且不含 num2 本身,字数之间的步长,以 setp 为准 (step 默认等于 1)
如:range(5, 10,2) 结果:【5,7,9】
python
# range(num)
for a in range(10):
print(a, end=' ')
# range(num1, num2)
for a in range(0, 10):
print(a, end=' ')
# range(num1, num2, step)
for a in range(0, 10, 2):
print(a, end=' ')
"""
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 2 4 6 8
"""
for循环临时变量作用域
python
# 在 for 循环外部访问循环内的临时变量
for i in range(5):
print(f'for 内部 i = {i}')
# 能直接访问,但不建议这样使用,不符合规范
print(f'for 外部 i = {i}')
# 改造后,将 i 变量定义出来
i = 0
for i in range(5):
print(f'for 内部 i = {i}')
# 能直接访问,但不建议这样使用,不符合规范
print(f'for 外部 i = {i}')
"""
for 内部 i = 0
for 内部 i = 1
for 内部 i = 2
for 内部 i = 3
for 内部 i = 4
for 外部 i = 4
"""
for循环嵌套
python
i = 1
for i in range(1, 101):
print(f'i love python, 表白的第{i}天')
for j in range(1, 11):
print(f'\t送你第{j}支花')
print(f'第{i}天表白成功')
for嵌套:九九乘法表
python
for i in range(1, 10):
for j in range(1, i+1):
print(f'{j} * {i} = {i * j}', end='\t')
print()
"""
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
"""