目录
1.打印语句
初级:打印多个变量,使用多个print() 语句。
a, b, c = 10, 5, 3
print(a)
print(b)
print(c)
# 10
# 5
# 3
进阶:合理使用print()的参数。sep参数指定使用相同打印语句(上面的 a、b 和c)打印的各种变量之间的分隔符;end参数用于指定print语句的结束符。
a, b, c = 10, 5, 3
print(a, b, c, sep = "\n")
# 10
# 5
# 3
print(a, end = "\n---\n")
print(b, end = "\n---\n")
print(c)
# 10
# ---
# 5
# ---
# 3
2.for循环打印相同的变量
初级:
repeat = 10
a = "ABC"
for _ in range(repeat):
print(a, end = "")
# ABCABCABCABCABCABCABCABCABCABC
进阶:
repeat = 10
a = "ABC"
print(a*repeat)
# ABCABCABCABCABCABCABCABCABCABC
3.单独变量跟踪循环索引
初级:创建range迭代器来跟踪索引
list = ["a", "b", "c", "d", "e", "f"]
for index in range(len(list)):
print("index =", index, "value =", list[index], sep = " ")
index += 1
# index = 0 value = a
# index = 1 value = b
# index = 2 value = c
# index = 3 value = d
# index = 4 value = e
# index = 5 value = f
进阶:使用enumerate()方法跟踪索引index和值i
list = ["a", "b", "c", "d", "e", "f"]
for index, i in enumerate(list):
print("index =", index, "value =", i, sep = " ")
# index = 0 value = a
# index = 1 value = b
# index = 2 value = c
# index = 3 value = d
# index = 4 value = e
# index = 5 value = f
4.for循环反转列表
初级:反向迭代列表并将元素添加到新列表
input_list = [1, 2, 3, 4, 5]
output_list = []
for idx in range(len(input_list), 0, -1):
output_list.append(input_list[idx-1])
print(output_list)
# [5, 4, 3, 2, 1]
进阶:Python 中的切片实现(reverse()方法也可以实现)
input_list = [1, 2, 3, 4, 5]
output_list = input_list[::-1]
print(output_list)
# [5, 4, 3, 2, 1]
input_list.reverse()
print(input_list)
# [5, 4, 3, 2, 1]
5.for循环获取字符串的子字符串
初级:
input_str = "ABCDEFGHIJKL"
start_index = 4
n_chars = 5
output_str = ""
for i in range(n_chars):
output_str += input_str[i+start_index]
print(output_str)
# EFGHI
进阶:
input_str = "ABCDEFGHIJKL"
start_index = 4
n_chars = 5
output_str = input_str[start_index:start_index+n_chars]
print(output_str)
# EFGHI