Python basics-07 (for loop, range() function)


Preface

This chapter introduces the most commonly used loop in the loop structure, the for loop.
At the same time, we introduce the range function that is often used with for loops.


1. for loop

1.for loop structure

'''
格式:
for 变量 in 需要遍历的数据:
    执行的代码
'''

'''
光看文字的话会比较抽象,直接举例子,很快就能理解
'''
# 例1
for i in '12345':
    print(i)
'''
结果
1
2
3
4
5
'''

# 例2
s = 'python'
for i in s:
    print(i)
'''
结果
p
y
t
h
o
n
'''

2. Parameter end='' (make it horizontal when output)

'''
要是想横着输出,在后面加上参数end=''
end=''的引号中间可以添加其他字符串,作为每次遍历后的分隔符,讲得比较抽象,结合看下面例子
'''
for i in s:
    print(i, end='')  # python

print('\n')

for i in s:
    print(i, end='牛的')  # p牛的y牛的t牛的h牛的o牛的n牛的

print('\n')

# range关键字
for i in range(5):
    print(i, end='')  # 01234

2. range() function

1.range(constant)

for i in range(5):
    print(i, end='')  # 01234

'''
会发现range(5)通过遍历打印出来的内容分别是 01234
也就是说range关键字会定义一个范围,range(n)从0开始一直至n-1,强调从0开始,即左闭右开区间
'''

2.range(start value, end value)

'''
还有一种写法,就是range(起始值,结束值)依然遵循左闭右开的原则
'''
for i in range(1, 5):
    print(i, end='')  # 1234

3.range(start value, end value, step size)

'''
还有一种写法,就是range(起始值,结束值,步长) 依然遵循左闭右开的原则
步长,顾名思义就是步子的长度,在range中就是每次跳过多少个元素
'''
for i in range(1, 10, 2):
    print(i, end='')  # 13579 即1-9每次跳过2个元素往后算

4.Examples

'''
循环一个列表,用列表下标的形式输出列表中的内容
'''

a_list = ['乔丹', '勒布朗', '哈登', '库里', '保罗']

# len()方法可以返回列表中的元素个数
len_list = len(a_list)
print(len_list)  # 5

for i in range(len_list):
    print(a_list[i])

Insert image description here


Summarize

1. Understand the structure format of for loop and understand the meaning of traversal
2.The principle of left closing and right opening of range function, as well as the meanings of three different parameters and their corresponding meanings of three different situations.

Guess you like

Origin blog.csdn.net/qq_45657848/article/details/135434791