Python data analysis combat 5.3-loop statement: for loop [python]

[Course 5.3] Loop statement: for loop

The for loop can traverse any sequence of items, such as a list or a string.

Iterate

1. What if I want to output "hello world" 5 times?

for i in range(5):
    print('hello world!')
-------------------------------------------------------------------
hello world!
hello world!
hello world!
hello world!
hello world!

2. Traverse the sequence and map by for

lst = list(range(10))
for i in lst[::2]:
    print(i)
print('-----')
# 遍历list

age = {'Tom':18, 'Jack':19, 'Alex':17, 'Mary':20}
for name in age:
    print(name + '年龄为:%s岁' % age[name])
# 遍历字典
-------------------------------------------------------------------
0
2
4
6
8
-----
Mary年龄为:20岁
Tom年龄为:18岁
Alex年龄为:17岁
Jack年龄为:19

3. Nested loop

for i in range(3):
    for j in range(2):
        print(i,j)
# 循环套循环,注意:尽量不要多于3个嵌套
-------------------------------------------------------------------
0 0
0 1
1 0
1 1
2 0
2 1
Published 36 original articles · praised 17 · visits 6274

Guess you like

Origin blog.csdn.net/qq_39248307/article/details/105476879