0
1
2
while
vs. for
loopsIn addition to while
, we can use for
to create loops
while
vs. for
loopsIn addition to while
, we can use for
to create loops
It iterates over the list, changing odd numbers to even number (even up).
Use a for
loop.
def make_all_even(integers):
# for each index in list
for index in range(len(integers)):
integers[index] += integers[index] % 2 # add zero if even, one if odd
return integers
def main():
test_integers = [1, 2, 3, 4]
assert make_all_even(test_integers) == [2, 2, 4, 4]
assert test_integers == [2, 2, 4, 4]
print(test_integers)
main()
[2, 2, 4, 4]
It returns a list of integers that represent the indices of the vowels in the string
Name file indices_of_vowels.py
and submit to Gradescope.
Use a for
loop.
Test cases:
def indices_of_vowels(string):
result = [] # initialize empty list to hold indices
# for every index in list
for index in range(len(string)):
if string[index] in "aeiou": # check if character is vowel
result.append(index) # append index to result
return result
def main():
assert indices_of_vowels("hello") == [1, 4]
assert indices_of_vowels("") == []
assert indices_of_vowels("aeiou") == [0, 1, 2, 3, 4]
main()
range()
Syntax: range(start, stop, step)
start
Optional. An integer specifying at which position to start. Default is 0stop
Required. An integer specifying at which position to stop (NOT included).step
Optional. An integer specifying the incrementation. Default is 1range()
It returns a new string with items at even indices in characters
concatenated together.
Use a for
loop.
Test cases:
It returns a new list in reversed order, containing items at every other index in the original list.
Use a for
loop.
Test cases:
def every_two(chars):
result = []
for i in range(len(chars)-1, -1, -2):
result.append(chars[i])
return result
def main():
characters = ["o", "e", "k", "l", "c", "p", "l", "p", "m", "a"]
assert every_two(characters) == ["a", "p", "p", "l", "e"]
assert every_two(["y", "e", "o", "e", "j"]) == ["j", "o", "y"]
print("pass the test case")
main()
pass the test case
Test cases: