Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 2023 June 3
- # 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) # print(item, end="\n")
- # tuples
- myTuple = ("Gilligan", "Castaway002", "red", "crew")
- for item in myTuple:
- print(item)
- # strings
- myString = "It was the best of times."
- # for char in myString:
- # print(char)
- # print(char)
- # print(char, end="\n")
- for char in myString:
- #print(char) # print(char, end="\n")
- print(char, end="->")
- print() # I add this!
- print("I wish this was on a clean new line by itself.")
- # Ch 2.9 and Lab 2.12
- # dictionaries
- # myDict = {"key": "value"}
- #
- # for key in myDict: # loop var in dict for loop holds the KEY
- # myDict[key] # retrieves value for that key
- # myDict[key] = value # assign a (new) value to 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:
- # "Check out Episode ___ or '___'"
- print("Check out Episode {} or '{}'".format(key, bestOfXF[key])) # value is bestOfXF[key]... myList[0]
- # help(str.format)
- # range objects... to just to do something X number of times
- for num in range(0, 5): # [0, 1, 2, 3, 4]
- print(num)
- myList = ["Agent Scully", "Agent Mulder", "Walter Skinner", "CSM", "Mr. X"]
- # if I need to know the index, then
- # for item in myList: # doesn't help!
- for i in range(0, len(myList)):
- print("{}: {}".format(i, myList[i]))
- # could also use ENUMERATE
- for i, item in enumerate(myList):
- print("{} - {}".format(i, item))
- for i in range(0, len(myList)):
- if i < len(myList) - 1:
- print("{} vs ".format(myList[i]), end="")
- else: # must be the last one!
- print(myList[i])
- print("I wish this was on a clean new line by itself.")
- print(" vs ".join(myList))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement