Create a loop that prints each of the elements of this list. Each iteration of the loop
Question:
Create a loop that prints each of the elements of this list. Each iteration of the loop should print one element of the list.
animals=["cat", "dog", "marmot", "donkey", "skunk", "dolphin", "snake"]
What to submit: Your Python code, as a file attachment.
----------------------------------------------------------------------------------------------
Here are Dr. Bill's intro slides re. Python loops.
Notes*
Looping in Python
Why looping? Sometimes we need to repeat a snippet of code many times
Terminology: This is a category of non-linear code execution called “Branching”
#(example adapted from #https://www.freecodecamp.org/news/python-do-while-loop-example/)
secret_word = "blah"
counter = 0
finished = False
while !finished:
word = input("Enter the secret word: ").lower()
counter = counter + 1
if word == secret_word:
finished = True
if word != secret_word and counter > 7:
finished = True
Looping through a list:
groceries= [“cherries", "banana", "walnuts", “ice cream”]
for x in groceries:
if x == "banana":
print(“Found a banana!”)
break
print(x)
print(“apples” in groceries)
Tuples:
Very much like lists but in most everyday forms are “immutable”, meaning their values cannot change.:
someNumbers = (0, 5, 9, 12)
someNumbers[3] # returns “12”
someNumbers[1] = 56 # invalid syntax, will give error
a = (16.78, “hello”, [15, 9, 12, 88])
# Valid. So the 3rd element changed. So is this tuple really immutable?
a[2].append(99)
Tuple example … note similarly with lists
allowed = ("RED", "GREEN", "BLUE")
tryThis = "ORANGE"
if tryThis in allowed:
print("OK, you may enter")
else:
print("STOP!")
range() type
Often mistaken for a function.
Actually an immutable data type
range(4) works very much like the tuple (0, 1, 2, 3)
>>> 2 in range(4)
True
Using tuples for list indices
#Looping through a list using list access operator,
# and range(len(words)) for the index bounds.
words = ["dojść", "spędzać", "czas", "sklep", "ale"]
for i in range(len(words)):
print(words[i])
What will this do?
for i in range(2, 6):
print(i**3)
Systems analysis and design
ISBN: 978-0136089162
8th Edition
Authors: kenneth e. kendall, julie e. kendall