Untitled
A look at for loops over various types of containers# 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 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) # range(5) --> range(0, 5, 1) ----> [0, 1, 2, 3, 4] # for num in range(0, 5, 1): # print(num) # Looping over an indexed container, and I need to know the INDEX # 2 choices... range() of len(), enumerate() # RANGE of LEN # for i 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 the key "someKey" # myDict["someKey"] = "someVal" # assigns value to 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: # 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 = [] # start the new container, empty, before the loop for item in myList: # filter with an if if "Agent" in item: agentList.append(item) print(agentList) season2 = {} for k in bestOfXF: if "2x" in k: season2[k] = bestOfXF[k] print(season2) # math questions in a range # How many numbers 0-100 are evenly divisible by 25? numList = [] for num in range(0, 101): if num % 25 == 0: numList.append(num) print(len(numList))
Leave a Comment