Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # # 2024 Feb 03
- # # 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)
- # 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 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 a value for 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:
- # key is key
- # bestOfXF[key] is its value
- # value = bestOfXF[key] # if you like
- # "Check out Episode ___ or '___'"
- print(f"Check out Episode {key} or '{bestOfXF[key]}'")
- # looping a known number of times
- # RANGE
- # range(start=0, stop, step=1)
- for num in range(0, 5): # [0, 1, 2, 3, 4]
- print(num)
- # Need to know index? Range of length
- myList.append("Krycek")
- myList.append("Queequeg")
- myList.append("Frohicke")
- for i in range(0, len(myList)):
- print(f"{i} is {myList[i]}")
- # process in pairs
- for i in range(0, len(myList), 2):
- print(f"{myList[i]} hates {myList[i+1]}")
- # another way to loop focused on the index
- for i, item in enumerate(myList):
- print(f"{i} --> {item}")
- # Common Pattern
- # "fill the basket"
- # make a new container from previous one
- newList = [] # start with empty new container
- for item in myList:
- # filter!
- # if item[0] == "a" or item[0] == "A":
- if item.lower().startswith("a"):
- newList.append(item)
- print(newList)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement