lst = [1, 2, 3, 4]
## Iteration through a list with a while loop ##
# Print elements
i = 0
while i < len(lst):
print(lst[i])
i += 1
def sum_of_evens(lst):
""" Return the sum of the even numbers in lst. """
i, total = 0, 0
while i < len(lst):
if lst[i] % 2 == 0:
total += lst[i]
i += 1
return total
## Iteration through a list with a for loop ##
# Print elements
for e in lst:
print(e)
def sum_of_evens_for(lst):
""" Return the sum of the even numbers in lst. """
total = 0
for e in lst:
if e % 2 == 0:
total += e
return total
## Iteration through a range ##
def print_odds(n):
""" Print all the odd numbers from 1 to n. """
for x in range(n):
if x % 2 == 1:
print(x)
def print_n_times(x, n):
""" Print the value of x n times. """
for _ in range(n):
print(x)