Gotchas For Loops Webinar, Jan 2025

 avatar
unknown
python
8 days ago
2.4 kB
5
Indexable
# 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, str, tuple, etc)

# Basic syntax of a for loop
# for ___ in _someContainer_: # for loop variable comes along with the structure

# For Loop variables (the word after the for keyword) are SPECIAL VARIABLES
# that come along with this loop

# # 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
# myStr = "It was the best of times."
# for char in myStr:
#     print(char)

# LOOP A NUMBER OF TIMES
# RANGE OBJECT... range()
# range(start=0, stop, step=1) # stop number is one beyond, excluded
# for num in range(5): # range(0, 5, 1) --> [0, 1, 2, 3, 4]
#     print(num)

# IF YOU NEED THE INDEX DURING THE LOOP
# 2 choices... range() of len(), enumerate()

# RANGE of LEN
# for i in range(len(myList)): # for ___ in range(0, len(myList), 1)
#     # print(i)
#     # print(myList[i])
#     print(f"{i}: {myList[i]}")

# ENUMERATE
# for i, item in enumerate(myList):
#     print(f"{i}--> {item}")

# What index is this value at in the list?
# print(myList.index("Mr. X"))

# DICT
# myDict = {
#     key: value,
#     key: value
# }
# myDict["someKey"] # retrieve the value associated with that key
# myDict["someKey"] = "someValue" # assign a value key

bestOfXF = {
    "1x00": "Pilot",
    "2x10": "Red Museum",
    "2x14": "Die Hand Die Verletzt",
    "2x20": "Humbug",
    "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: # loop var hold key
#     # print(key)
#     # print(bestOfXF[key])
#     # "Check out Episode ___ or '---'."
#     print(f"Check out Episode {key} or '{bestOfXF[key]}'.")

# EXTRA... this is a general pattern you'll use a lot with all types of containers
# FILL THE BASKET / FILTER
agentList = []
for item in myList:
    # filter with an if
    if "Agent" in item:
        agentList.append(item)
print(agentList)
Leave a Comment