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))