python小课堂:12 Python之for循环

Python之for循环
更新于: 2022-08-13 13:13:17

循环

举个例子,当我们需要把字符串中的每一个字符打印出来的时候,我们怎么实现呢?

s = 'ABCD'
print(s[0])
print(s[1])
print(s[2])
print(s[3])

几种常见数据结构

  • 数组: [1,2,3,4,5,6,7]
  • 字符串: “ABCDE”
  • range: range(1,10)
  • 字典?

数组/字符串的循环

arr = [ 1,2,3,4 ]
for item in arr:
    print(item)
arr = [ 
    "a",
    "b",
    "c",
    "d",
    "e" 
]

# 数组的长度: len(arr)
# 数组的第一个元素: arr[0]
# 数组的最后一个元素: arr[-1]
# 数组的第二个元素: arr[1]

输出数组索引

  • 索引:对应元素的位置,也称下标
arr = [ 
    "a",
    "b",
    "c",
    "d",
    "e" 
]

for i in range(len(arr)):
    print(i, arr[i])

# 0 a
# 1 b
# 2 c
# 3 d
# 4 e

字符串的循环

str1 = "abcdefg"

# loop string
for i in str1:
    print(i)

范围 range

r1 = range(1, 10)

for i in r1:
    print(i)

字典

dict1 = {
    "键":"值",
    "key":"value",
    "a": "小写字母a",
    "b": "小写字母b",
    "c": "小写字母c",
    "d": "小写字母d",
}

for item in dict1:
    print(item, dict1[item])

语法

for 变量 in 数据:
  # 变量: 每一项的数据
  print(变量)

练习

scores = [75, 92, 59, 68, 99]

# 利用 for 循环,计算出总分, 计算出平均成绩
# 1. 数据是一个数组
# 2. 计算出总分
# sum1 = scores[0] + scores[1] + scores[2] + scores[3] + scores[4]
n1 = scores[0] # 75
n2 = scores[1] # 92
n3 = scores[2] # 59
n4 = scores[3] # 68
n5 = scores[4] # 99

sum1 = n1 + n2 + n3 + n4 + n5
for 循环的执行过程

参考