For Loops 2024 Nov 9
unknown
python
6 months ago
2.5 kB
4
Indexable
# WEBINAR: For Loops 2024 Nov 9 # 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 # 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) # DICT # myDict = { # key: value, # key: value, # key: value # } # myDict[key] # get the value for that key # myDict[key] = value # assign value to key # for ___ in myDict: # what does the loop var hold when looping over a dict? 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 ___ in thisDict: # for key in bestOfXF: # # print(key) # # print(bestOfXF[key]) # # "Check out Episode ___ or '---'." # print(f"Check out Episode {key} or '{bestOfXF[key]}'") # Loop a known of number of times # RANGE # range(start=0, stop, step=1) # range(5) # range(0, 5, 1) --> [0, 1, 2, 3, 4] # for num in range(5): # print(num) # Looping over a container and I need to know the index # RANGE of LEN myList.append("Kyrcek") # for i in range(len(myList)): # # print(i) # # print(myList[i]) # print(f"{i}: {myList[i]}") # ENUMERATE # for i, item in enumerate(myList): # print(f"{i} --> {item}") # FILL THE BASKET / FILTER agentList = [] # start a new container for item in myList: # filter with an if if "Agent" in item: agentList.append(item) print(agentList) # comprehension # A comprehension is just a condensed way of doing the "for loop to fill one container based on another" that we just did above # (I rarely use them) agentList = [item for item in myList if "Agent" in item] print(agentList) strNums = ["1", "3", "24"] numList = [int(num) for num in strNums] for num in strNums: numList.append(int(num)) print(numList)
Editor is loading...
Leave a Comment