Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 2023 Nov 4
- # 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 of times."
- for char in myString:
- print(char)
- for char in myString:
- # if not char.isspace():
- if char.isalpha():
- print(char)
- # for key in myDict:
- # # myDict[key]
- # # myDict[key] = value
- 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 k in bestOfXF:
- # "Check out Episode ___ or '___'"
- print(f"Check out Episode {k} or '{bestOfXF[k]}'")
- # membership check... in
- print("5x05" in bestOfXF) # True... b/c key is in dict
- print("6x01" in bestOfXF) # False
- print("All Souls" in bestOfXF) # False... that is not KEY in this dict
- # if I wanted to check if something is present as a dict VALUE
- # myDict.values() - returns a special container type with just the values
- print("All Souls" in bestOfXF.values()) # True
- # what is the VALUE for this KEY
- # we can get that directly: myDict[key]
- print(bestOfXF["5x05"])
- # what is the KEY for this VALUE
- # loop through dict and check each value, remember the key where found
- # say I got "All Souls" from input(), is it a value and what's the key?
- for key in bestOfXF:
- if bestOfXF[key] == "All Souls":
- print(key)
- # if I make it this far without finding it, I can say it's not there
- # range()... a range object, which we use to loop a number of times
- # range(0, 5) # [0, 1, 2, 3, 4]
- for num in range(5):
- print(num)
- # using range() to correspond to index
- for i in range(len(myList)):
- # print(myList[i])
- 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}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement