# 2023 Sept 9 # 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, str, tuples, sets, dictionary, range objects) # Basic syntax of a for loop # for ___ in _someContainer_: # 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\n of times." for char in myString: # print(char) # print(f"{char} is alphabetical? {char.isalpha()}") print(f"{char} is a kind of whitespace? {char.isspace()}") # dictionaries # {key:value, key:value} # myDict[key] # retrieve the value for that key # myDict[key] = value # assign a value for that key # for _key_ in myDict: 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: # "Check out Episode ___ or '___'" # var key holds each key as I loop # corresponding value is bestOfXF[key] val = bestOfXF[key] # print(f"Check out Episode {key} or '{bestOfXF[key]}'") print(f"Check out Episode {key} or '{val}'") # range()... a range object, which we use to loop a number of times for num in range(0, 5): # --> [0, 1, 2, 3, 4] print(num) # using range() to correspond to index for i in range(len(myList)): print(f"Position {i} is: {myList[i]}") # or... use enumerate() to get index and value for i, item in enumerate(myList): print(f"Position {i} is --> {item}")