定义一个列表[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
遍历列表,取出偶数,并存入一个新的列表对象中
使用while循环和for循环分别操作
通过if判断偶数
通过列表append方法增加元素
list = []
i=0
for i in range(1,11):
list.append(i)
i += 1
print(list)
list1 = []
def one():
index = 0
while index <= len(list) - 1:
if list[index] % 2 == 0:
a = list[index]
list1.append(a)
index += 1
print(list1)
def two():
for i in list:
if i % 2 == 0:
list1.append(i)
i += 1
print(list1)
# one()
two()
以下是运行结果
E:\Anaconda\python.exe D:\pythoncode\test.py
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 4, 6, 8, 10]
进程已结束,退出代码0
使用python的时候,要特别注意缩进
index += 1是一个循环继续的条件
for循环里面的i是元素
但是while是索引,所以要list[index]
刚开始时候用while写出来不是我想要的答案
因为我用了pop,pop的话,他每次都会取出来list里面的元素,那么你再循环一次的时候,list不是原来的列表,里面的元素已经取出来,比如第一次取出了2,那么你下次的list循环就会变成[1, 3, 4, 5, 6, 7, 8, 9, 10],你的index是1,你想要的元素是2,但是取出来的是3,就错误了。以下是在学习中截的图,需要用到可以参考一下