coursesa课程 Python 3 programming The while Statement

这篇博客探讨了Python 3编程中的while循环。首先,介绍了如何编写一个从0开始,停止于15的while循环,当计数器为偶数时将其添加到eve_nums列表中。接着,通过一个while循环实现与for循环相同的功能,即累加list1的所有元素,累加器变量命名为accum。最后,讲解了一个名为stop_at_four的函数,该函数使用while循环遍历包含数字的列表,直到遇到数字4,将所有遍历到的数字添加到新列表并返回。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、Write a while loop that is initialized at 0 and stops at 15. If the counter is an even number, append the counter to a list called eve_nums

n = 0
eve_nums = list()
while n <= 15:
    if n % 2 == 0:
        eve_nums.append(n)
    n = n + 1
print(eve_nums)

2、Below, we’ve provided a for loop that sums all the elements of list1. Write code that accomplishes the same task, but instead uses a while loop. Assign the accumulator variable to the name accum.


list1 = [8, 3, 4, 5, 6, 7, 9]

tot = 0
for elem in list1:
    tot = tot + elem

accum = 0
count = 0
while count < len(list1):
    accum = accum + list1[count]
    count = count + 1
print(accum)

3、Write a function called stop_at_four that iterates through a list of numbers. Using a while loop, append each number to a new list until the number 4 appears. The function should return the new list.

def stop_at_four(lst):
    count = 0
    lst1 = list()
    while lst[count] != 4:
        if count < len(lst):
            lst1.append(lst[count])     
        count = count + 1
    return lst1

lst = [1,2,3,4,5,6]
print(stop_at_four(lst))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值