笨办法学Python3 习题32 循环和列表

发布时间 2023-10-11 21:18:02作者: 萹豆

知识点:

  • for  i  in  y :  # for循环开始 i 变量就被创建,所以不用提前创建
  • 只有在for 循环里有效
  • range(,)函数会从第一个数到最后一个之前的数,不包含最后一个数
  • Y.append(X) 将X 追加到列表Y的尾部
 1 the_count = [1,2,3,4,5]                      # 创建3个列表变量
 2 fruits = ['apples','orange','pears','apricots']
 3 change = [1,'pennies',2,'dimes',3,'quarters']
 4 
 5 for number in the_count:                     # 循环第一个列表
 6     print(f"This is count {number}")
 7 
 8 for fruit in fruits:
 9     print(f"A fruit of type : {fruit}")      # 循环第二个列表
10 
11 for i in change:                             # 循环第三个列表
12     print(f"I got {i}") 
13     
14 elements = []                                # 循环外创建空列表
15 
16 for i in range(2,15):                        # range()函数会从第一个数到最后一个之前的数,不包含最后一个数
17     print(f"Adding {i} to the list.")     
18     elements.append(i)                       # i 进行循环的同时,空列表尾部追加 i
19 
20 for i in elements:                           # 用循环查看之前的空列表是否被复制好填完整
21     print(f"Element was : {i}")
PS C:\Users\Administrator\lpthw> python ex32.py
This is count 1
This is count 2
This is count 3
This is count 4
This is count 5
A fruit of type : apples
A fruit of type : orange
A fruit of type : pears
A fruit of type : apricots
I got 1
I got pennies
I got 2
I got dimes
I got 3
I got quarters
Adding 2 to the list.
Adding 3 to the list.
Adding 4 to the list.
Adding 5 to the list.
Adding 6 to the list.
Adding 7 to the list.
Adding 8 to the list.
Adding 9 to the list.
Adding 10 to the list.
Adding 11 to the list.
Adding 12 to the list.
Adding 13 to the list.
Adding 14 to the list.
Element was : 2
Element was : 3
Element was : 4
Element was : 5
Element was : 6
Element was : 7
Element was : 8
Element was : 9
Element was : 10
Element was : 11
Element was : 12
Element was : 13
Element was : 14