Gotchas: For Loops 2024 08 03
A basic loop at for loopsunknown
python
a year ago
2.3 kB
20
Indexable
# # 2024 Aug 4
# # WEBINAR: For Loops
#
# # We use loops to repeat actions
# a WHILE loop... is an IF that repeats as long as the loop condition remains True
# FOR LOOPS are used for repeating actions for every element in a container (list, dict, tuple, str, range, etc)
# Basic syntax of a for loop
# for ___ in _someContainer_:
# For Loop variables (the word after the for keyword) are SPECIAL VARIABLES that come along with this loop structure
# # LIST
myList = ["Agent Scully", "Agent Mulder", "Walter Skinner", "CSM", "Mr. X"]
# for item in myList:
# print(item)
#
# # TUPLE
# myTuple = ("Gilligan", "Castaway002", "red", "crew")
# for item in myTuple:
# print(item)
#
# # STRING
# myString = "It was the best of times."
# for char in myString:
# print(char)
# DICT
# myDict = {
# key: value,
# key: value,
# key: value
# }
# myDict[key] # get the value for that key
# myDict[key] = value # assign value to that key
bestOfXF = {
"1x00": "Pilot",
"2x10": "Red Museum",
"2x14": "Die Hand Die Verletzt",
"3x04": "Clyde Bruckman's Final Repose",
"3x12": "War of the Coprophages",
"3x20": "Jose Chung's From Outer Space",
"4x05": "The Field Where I Died",
"5x05": "The Post Modern Prometheus",
"5x17": "All Souls"
}
# for key in bestOfXF:
# # myDict[key] ... bestOfXF[key] to get the value
# "Check out Episode ___ or '---'."
# print(f"Check out Episode {key} of '{bestOfXF[key]}'.")
#
# # Membership checkc: is x in myList?
# print("5x05" in bestOfXF) # True
# print("All Souls" in bestOfXF) # False... in keyword does not look at values
# print(bestOfXF.values()) # to see a container of just dict values... not needed very often
# Loop a known of number of times
# RANGE
# range(start=0, stop, step=1)
# for n in range(5): # range(5) --> range(0, 5, 1) --> [0, 1, 2, 3, 4]
# print(n)
# Looping over a container and I need to know the index
# RANGE... OF LEN()
for i in range(len(myList)): # range(0, len(myList), 1)
print(f"{i}: {myList[i]}")
# ENUMERATE
for i, item in enumerate(myList):
print(f"{i}--> {item}")
# FILL THE BASKET / FILTER - a pattern you'll use a lot
myNewList = []
for item in myList:
# filter with if
if item.startswith("Agent"):
myNewList.append(item)
print(myNewList)
Editor is loading...
Leave a Comment