1、循环语句
1.1 for循环
for 变量 in 集合:
将集合中的数值一一赋值给变量
例:
# 对于整数
for i in range(0, 10, 2): # 从零开始,到10结束,步进值为2,打印偶数
print(i)
# 输出结果
0
2
4
6
8
# 对于字符串(独有)
name="Alice"
for x in name:
print(x, end="")
#输出结果
Alice
# 对于列表
a = ["A", "B", "C"]
for i in range(len(a)):
print(f"a[{i}]={a[i]}")
#输出结果
a[0]=A
a[1]=B
a[2]=C
2、while循环
python中的while循环与大多数语言相似,格式:
while 条件 :内容
例:
# 基本例子
i = 0
while i < 5:
print("当前是第%d次执行循环" % (i+1))
print("i = %d"% i )
i += 1
#输出结果
当前是第1次执行循环
i = 0
当前是第2次执行循环
i = 1
当前是第3次执行循环
i = 2
当前是第4次执行循环
i = 3
当前是第5次执行循环
i = 4
# 1至100求和
a = 1
Sum = 0
while a <= 100:
Sum += a
a += 1
print(Sum)
#输出结果
5050
# whlie语句中的else
count = 0
while count < 5:
print(count, "<5")
count += 1
else:
print(count, ">=5")
# while语句中的break
i = 0
while i < 10:
i = i+1
print("*"*10)
if i == 5:
break #直接退出整个while语句
print(i)
#输出结果
**********
1
**********
2
**********
3
**********
4
**********
# while语句中的continue
i = 0
while i < 10:
i = i+1
print("*"*10)
if i == 5:
continue #下方的语句不再执行,返回while语句首句接着执行
print(i)
#输出结果
**********
1
**********
2
**********
3
**********
4
**********
**********
6
**********
7
**********
8
**********
9
**********
10