for循环结构_遍历各种可迭代对象_range对象

for 循环通常用于可迭代对象的遍历。for 循环的语法格式如下:
for 变量 in 可迭代对象:
    循环体语句
    
Python中可迭代对象:
1、序列。包含:字符串、列表、元组
2、字典
3、迭代器对象(iterator)
4、生成器函数(generator)
5、文件对象

for x in (10,20,30):     #for循环遍历元组
    print(x*2,end="\t")

for x in "ABCDE":        #for循环遍历字符串
    print(x,end="\t")

for x in list("abcde"):  #for循环遍历列表
    print(x,end="\t")

d={"name":"Vince","age":18,"job":"Student"}
for x in d:              #for循环遍历字典
    print(x)

for x in d.keys():       #for循环遍历字典的键
    print(x)

for x in d.values():     #for循环遍历字典的值
    print(x)

for x in d.items():     #for循环遍历字典的键值对
    print(x)


#for循环遍历range()迭代对象
sum=0
sum_odd=0    #偶数和
sum_even=0   #奇数和
for x in range(101):
    sum+=x
    if x%2==0:
        sum_odd+=x
    else:
        sum_even+=x
print("总数和为{0},偶数和为{1},奇数和为{2}".format(sum,sum_odd,sum_even))

转载于:https://www.jianshu.com/p/9329042c0ee0

猜你喜欢

转载自blog.csdn.net/weixin_34067980/article/details/91259732