python for loop

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/sehanlingfeng/article/details/91175382

# 循环语句 while,for

# for循环

a = '12345'                    		# 字符串
for c in a:		
    print(c)                   		# c从a中每次取一个元素打印出来 1 2 3 4 5
		
b = [1, 2, 3, 4]               		# 列表
		
for c in b:		
    print(c)                   		# c从b中每次取一个元素打印出来 1 2 3 4
		
d = ('a', 'b', 'c', 'd')       		# 元组
for c in d:		
    print(c)                   		# c从d中每次取一个元素打印出来 a b c d
		
e = {                          		# 字典
    1: 'a',		
    2: 'b',		
    3: 'c'		
}		
for c in e:		
    print(c)                   		# c从d中每次取一个key打印出来 1 2 3
# 如果要从字典里取出value		
		
for c in e.items():		
    print(c)                   		# c获取字典中每一组key和value,以元组的形式打印出来: (1, 'a')(2, 'b')(3, 'c')
		
for m, n in e.items():		
    print('{}={}'.format(m, n))		# m和n获取到key和value,打印如下 1=a 2=b 3=c
		
f = {1, 2, 3, 5, 9}            		# 集合
for item in f:		
    print(item)                		# 循环打印出集合的值 1 2 3 5 9
		
for item in range(1, 20, 4):   		# 第一个参数是开始值1,第二个参数结束值20,第三个参数步长4
    print(item)                		# 循环打印1到20步长为4的值: 1 5 9 13 17 ,如果循环能取到20,则不打印20,相当于[1,20)

 

Guess you like

Origin blog.csdn.net/sehanlingfeng/article/details/91175382
Recommended