# Python中的for循环用法详解，一文搞定它

## for循环

for循环可以解决while循环的局限性

#while循环在遍历数据时的局限性

lst = [1,2,3,4,5]  # ok
i = 0
while i < len(lst):
print(lst[i])
i+=1


setvar = {"a","b","c"} # not ok
i = 0
while i < len(setvar):
print(setvar[i])
i+=1


### 1.for循环的基本语法

Iterable 可迭代性数据：1.容器类型数据 2.range对象 3.迭代器

for 变量 in Iterable:
code1
#字符串
container = "北京和深圳温差大概20多度"
#列表
container = [1,2,3,4,4,5]
#元组
container = ("孙开洗","孙健","孙悟空")
#集合
container = {"陈璐","曹静怡","王志国","邓鹏","合力"}
#字典
container = {"cl":"风流倜傥","cjy":"拳击选手","wzg":"寻花问柳","dp":"帅气,祖国的栋梁","hl":"你是个好人"}


#遍历数据

for i in container:
print(i)

#### （1）遍历不等长多级容器

container = [1,2,3,4,("嗄","234",{"马春配","李虎凌","刘子涛"})]
for i in container:
# 判断当前元素是否是容器,如果是,进行二次遍历,如果不是,直接打印
if isinstance(i,tuple):
# ("嗄","234",{"马春配","李虎凌","刘子涛"})
for j in i:
# 判断当前元素是否是集合,如果是,进行三次遍历,如果不是,直接打印
if isinstance(j,set):
# j = {"马春配","李虎凌","刘子涛"}
for k in j :
print(k)
else:
print(j)

# 打印数据
else:
print(i)


#### （2）遍历不等长多级容器

container = [("刘玉波","历史源","张光旭"), ("上朝气","于朝志"),("韩瑞晓",)]
for i in container:
for j in i:
print(j)


#### （3）遍历等长的容器

container = [("马云","小马哥","马春配") , ["王健林","王思聪","王志国"],{"王宝强","马蓉","宋小宝"}]
for a,b,c in container:
print(a,b,c)

### 2.变量的解包

a,b,c = "poi"
a,b = (1,2)
a,b = 1,2
a,b,c = [10,11,12]
a,b = {"林明辉","家率先"}
a,b = {"lmh":"林明辉","jsx":"家率先"}
a,b,c = ("马云","小马哥","马春配")
print(a,b,c)


### 3.for…else【详细讲解】

for 临时变量 in 序列:
重复执行的代码
......
else:
循环正常结束后要执行的代码


### 4.range对象

range([开始值,] 结束值 [,步长])

#range(一个值)  默认从0开始
for i in range(5): # 0 ~ 4
print(i)


#range(二个值)
for i in range(3,8): # 3 4 5 6 7
print(i)

#range(三个值) 正向的从左到右
for i in range(1,11,3): # 1 4 7 10
print(i)

#range(三个值) 逆向的从右到左
for i in range(10,0,-1): # 10 9 8 7 ... 1
print(i)


### 5.总结

while 一般用于处理复杂的逻辑关系

for 一般用于迭代数据

i = 1
while i <= 9:
j = 1
while j <= i:
print("%d*%d=%2d " % (i,j,i*j) ,end="" )
j+=1
print()
i +=1

for i in range(1,10):
for j in range(1,i+1):
print("%d*%d=%2d " % (i,j,i*j) ,end="" )
print()


for循环乘法口诀

### 6.打印 1 ~ 10 跳过5

i = 1
while i <= 10:
if i == 5:
i += 1
continue
print(i)
i +=1

for i in range(1,11):
if i == 5:
continue
print(i)


### 7.打印菱形小星星

     *
***
*****
*******
*********
***********
***********
*********
*******
*****
***
*


13 -> 7

11 -> 6

9 -> 5

7 -> 4

1 => 5

2 => 4

3 => 3

4 => 2

5 => 1

6 => 0

1 => 1

2 => 3

3 => 5

4 => 7

n = 13
hang = n // 2 + 1
i = 1
while i <= hang:
# 打印空格
kongge = hang - i
print(" " * kongge, end="")

# 打印星星
xingxing = 2 * i - 1
print("*" * xingxing, end="")

# 打印换行
print()
i += 1

i = hang
while i >= 1:
# 打印空格
kongge = hang - i
print(" " * kongge, end="")

# 打印星星
xingxing = 2 * i - 1
print("*" * xingxing, end="")

# 打印换行
print()
i -= 1


#打印菱形

     *
***
*****
*******
*********
***********
***********
*********
*******
*****
***
*


n = 2*hang - 1
kongge = hang - i
xingxing = 2*i -1

n = 13
hang = int((n + 1) / 2)
i = 1
while i <= hang:
kongge = hang - i
print(" " * kongge,end='')
xingixng = 2*i - 1
print(f"*"* xingixng,end='')
print()
i += 1

i = hang
while i >= 1:
kongge = hang - i
print(" " * kongge,end='')
xingixng = 2*i - 1
print(f"*"* xingixng,end='')
print()
i -= 1


   *
* *
* * *
* * * *
* * * *
* * *
* *
*


kongge = n - i

hang = 5
i = 1
while i <= hang:
kongge = hang - i
print(f" " * kongge,end='')
xingxing = i
if i == 1:
print("*",end='')
else:
j = 1
while j <= 2*i -1:
if j % 2 == 1:
print("*",end='')
else:
print(" ",end='')
j += 1
print()
i += 1

i = hang
while i >= 1:
kongge = hang - i
print(f" " * kongge,end='')
xingxing = i
if i == 1:
print("*",end='')
else:
j = 1
while j <= 2*i -1:
if j % 2 == 1:
print("*",end='')
else:
print(" ",end='')
j += 1
print()
i -= 1


|
28天前
|

Python接口自动化测试框架（基础篇）-- 流程控制之循环语句for&while

34 1
|
14天前
|
Python
python基本用法
【9月更文挑战第5天】python基本用法
34 7
|
29天前
|
Python

【8月更文挑战第21天】Python中的循环结构——for循环与while循环，是编程的基础。for循环擅长遍历序列或集合中的元素，如列表或字符串；而while循环则在未知循环次数时特别有用，基于某个条件持续执行。本文通过实例展示两种循环的应用场景，比如用for循环计算数字平方和用while循环计算阶乘。此外，还通过案例分析比较了两者在处理用户输入任务时的不同优势，强调了根据实际需求选择合适循环的重要性。
37 0
|
4天前
|

Python用法
Python用法
18 10
|
6天前
|

11个Python循环技巧

15 4
|
28天前
|

Python基础编程：冒泡排序和选择排序的另一种while循环实现

16 2
|
21天前
|
Python
Python 中 help() 和 dir() 函数的用法
【8月更文挑战第29天】
18 5
|
22天前
|

python Django教程 之模板渲染、循环、条件判断、常用的标签、过滤器
python Django教程 之模板渲染、循环、条件判断、常用的标签、过滤器
16 1
|
2天前
|

8 0
|
22天前
|
C语言 Python
Python 实现循环的最快方式（for、while 等速度对比）
Python 实现循环的最快方式（for、while 等速度对比）
34 0