Introduction to Python Programming (020) - Loop Structure Programming (1): for loop
Table of contents
1. Syntax of for loop
The for loop is a counted loop, suitable for enumerating or traversing elements in sequences and iteration objects. It is generally used when the number of loops is known. The syntax format of the for loop is as follows:
for 迭代变量 in 对象:
循环体
illustrate:
(1) Iteration variable: used to save the read value.
(2) Object: The object to be traversed or iterated can be any ordered sequence object, such as: string, list, tuple, etc.
(3) Loop body: a set of statements that need to be executed repeatedly.
(4) Python uses code indentation and colon (:) to distinguish code levels. The colon at the end of the for loop expression line and the indentation of the next line (usually 4 spaces are used as an indentation amount) indicate the beginning of a code block, and the end of the indentation indicates the end of a code block. When using a for loop, the code must be written strictly according to the indentation rules.
For example:
(1) Extract numbers, letters, English symbols and other characters in the string.
str1 = "ds3,3jH.iee/我fj*32的&号30U,码河。……H54南"
digit = ""
letter = ""
pun = ""
other = ""
for item in str1:
if ord(item) in range(48,58): # 数字的ASCII码为48-57
digit += item
elif ord(item) in range(65,91) or ord(item) in range(97,123): # 大写字母的ASCII码为65-90,小写字母的ASCII码为97-122
letter += item
elif ord(item) < 128: # 去除数字和字母
pun += item
else: # 其他字符(ASCII码大于127)
other += item
print("数字为:",digit)
print("字母为:",letter)
print("英文字符为:",pun)
print("其他字符:",other)
程序的运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
数字为: 33323054
字母为: dsjHieefjUH
英文字符为: ,./*&
其他字符: 我的号,码河。……南
(2) Traverse list data
list1 = ["Tom","Jerry","Kate","Black"]
for item in list1:
print(item)
print("="*30)
for item in range(len(list1)):
print(list1[item])
程序的运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
Tom
Jerry
Kate
Black
==============================
Tom
Jerry
Kate
Black
(3) Traverse tuple data
tuple1 = (["Tom",20],["Jerry",22],["Kate",18],["Black",19])
for item in tuple1:
print("Name:",item[0],"\tAge:",item[1])
print("="*30)
for item in tuple1:
print("姓名:{}\t年龄:{}".format(item[0],item[1]))
print("="*30)
for item in tuple1:
for i in item:
print(i,end="\t")
print()
程序的运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
Name: Tom Age: 20
Name: Jerry Age: 22
Name: Kate Age: 18
Name: Black Age: 19
==============================
姓名:Tom 年龄:20
姓名:Jerry 年龄:22
姓名:Kate 年龄:18
姓名:Black 年龄:19
==============================
Tom 20
Jerry 22
Kate 18
Black 19
(4) Traverse dictionary data
dict1 = {
"Tom":20,"Jerry":22,"Kate":18,"Black":19}
for key in dict1.keys():
print("Name:{}\tAge:{}".format(key,dict1.get(key)))
print("="*30)
for item in dict1.items():
print("Name:{}\tAge:{}".format(item[0],item[1]))
程序的运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
Name:Tom Age:20
Name:Jerry Age:22
Name:Kate Age:18
Name:Black Age:19
==============================
Name:Tom Age:20
Name:Jerry Age:22
Name:Kate Age:18
Name:Black Age:19
2. Use the range() function in the for loop
The for loop iterates through each element in the object by iterating through the variables. When iterating through an object by index, the range() function is often used to generate a consecutive series of integers. The format of the range() function is as follows:
range([start,] end[, step])
说明:
(1)start:指定计数的起始值。如果省略,则从0开始计数。
(2)end:指定计数的结束值,该参数不能省略,当函数中只有一个参数时即表示技术的结束值。生成的序列不包括结束值。比如 range(5),生成的序列为[0-4],range(1,11),生成的序列为[1-10]。
(3)step:指定步长,即两个数之间的间隔,如果省略则步长为1。
(4)在使用 range() 函数时,如果只有一个参数,则指定的是end;如果有两个参数,则指定的是start和end;指定三个参数时,第一个参数为start,第二个参数为end,第三个参数为step。
For example:
(1) Traverse list elements
list1 = ["Tom","Jerry","Kate","Black"]
for i in list1:
print("{}".format(i),end="\t")
print()
print("="*30)
for i in range(len(list1)):
print("{}".format(list1[i]),end="\t")
程序的运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
Tom Jerry Kate Black
==============================
Tom Jerry Kate Black
(2) Calculate 5! (1*2*3*4*5)
f = 1
for i in range(1,6):
f *= i
print("5!结果为:",f)
程序的运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
5!结果为: 120
(3) Calculate the sum of all odd numbers from 1-100
sum1 = 0
for i in range(1,101,2):
sum1 += i
print("1-100的和:",sum1)
程序的运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
1-100的和: 2500
3. for…else statement
A for loop can add an else branch statement. The else statement will be executed only after the for loop statement is executed normally. If a break or exit(0) statement is encountered in the for loop statement and the conditions for exiting are met, the else statement will not be executed. The syntax format of the for ... else statement is as follows:
for <迭代变量> in <遍历结构>:
语句块1
else:
语句块2
Note: The statement following else will be executed after the for loop execution is completed.
For example:
(1) The else statement is executed
code show as below:
num = 97
for i in range(2,int(num**0.5) + 1):
if num % i == 0:
break
else:
print("{}是一个素数。".format(num))
程序的运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
97是一个素数。
(2) The else statement is not executed
num = 95
for i in range(2,int(num**0.5) + 1):
if num % i == 0:
print("{}不是一个素数。".format(num))
break
else:
print("{}是一个素数。".format(num))
程序的运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
95不是一个素数。
4. for expression
The for expression can create a new sequence using an iterable object. The for expression is also called a sequence recursion. The syntax format is as follows:
[表达式 for 迭代变量 in 可迭代对象 [if 条件表达式] ]
For example:
(1) Find prime numbers between 2-100
list1 = [2]
for i in range(3,101):
if 0 not in [i%j for j in range(2,int(i**0.5) + 1)]:
list1.append(i)
print(list1)
程序的运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
(2) Process list data
list1 = ["Tom","Jerry","Kate","Black"]
list2 = ["Name:" + item for item in list1]
print(list2)
程序的运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
['Name:Tom', 'Name:Jerry', 'Name:Kate', 'Name:Black']
(3) Use the zip() function to combine multiple lists
list1 = ["Tom","Jerry","Kate","Black"]
list2 = [21,20,18,19]
list3 = [name + ":" + str(age) for name,age in zip(list1,list2)]
print(list3)
程序的运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
['Tom:21', 'Jerry:20', 'Kate:18', 'Black:19']
(4) Conditions used in for expressions
list1=[x ** 2 for x in range(1,10) if x % 2 == 0] # 返回1-9之间偶数的平方组成的列表
num = [2*x if x>=2 and x<=5 else x**2 for x in range(1,11)] # 如果x的值介于2和5之间返回 2*x,否则返回 x**2
print(list1)
print(num)
程序的运行结果为:
===================== RESTART: C:\Python\Python38\First.py =====================
[4, 16, 36, 64]
[1, 4, 6, 8, 10, 36, 49, 64, 81, 100]