循环基础题

练习:取出列表内的偶数定义一个列表,内容是:[1,2,3,4,5,6,7,8,9,10]     遍历列表,取出列表内的偶数,并存入一个新的列表中。     使用for循环和while循环各做一次

 一. 使用While循环解题

代码:

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list2 = []
def new_list():
    index = 0
    while index < len(list1):
        if list1[index] % 2 == 0:
            list2.append(list1[index])
        index += 1
    return list2
print(new_list())

结果: 

 

1. 定义题目中的列表和一个空列表

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list2 = []

2.定义函数

def new_list():

3.定义下标索引为0 

    index = 0

4.当下标< 列表的长度

    while index < len(list1):

 5.判断列表中的值除于2的值是否有余数

        if list1[index] % 2 == 0:

 6.把list1中的元素添加到空列表中

            list2.append(list1[index])

 7.循环一次 index+1

        index += 1

8.返回list2的值,并打印

    return list2
print(new_list())

二. 接下来是For循环的做法:

代码:

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list2 = []
def new_list1():
    for i in list1:
        if i % 2 == 0:
            list2.append(i)
    return list2
print(new_list1())

结合While循环做法步骤,很快就出答案

输出:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值