Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 2022 Oct 8
- # WEBINAR: For Loops
- # We use loops to repeat actions
- # a WHILE loop... btw.. is basically an IF statement
- # that repeats as long as its condition is true
- # FOR LOOPS are used for repeating actions for every element
- # in a container like a list, string, tuple, etc...
- # Basic syntax of a for loop
- # for __ in _someContainer_:
- myList = ["Agent Scully", "Agent Mulder", "Walter Skinner", "CSM", "Mr. X"]
- for item in myList:
- print(item) # print(end="\n")
- for item in myList:
- print(item, end=" ")
- print()
- print("Something else on a clean line...")
- # tuples
- myTuple = ("Gilligan", "Castaway002", "red", "crew")
- for item in myTuple:
- print(item)
- # strings
- myString = "It was the best of times. \nIt was the\t worst of times."
- # for char in myString:
- # print(char)
- # side note: string is___() methods
- for char in myString:
- if char.isupper():
- print(char)
- # "fill the basket" of a new container
- newStr = ""
- for char in myString:
- if not char.isspace():
- newStr += char
- print(newStr)
- # use str.replace()
- # just a literal space... myString = myString.replace(" ", "")
- for char in myString:
- if char.isspace():
- myString = myString.replace(char, "")
- print(myString)
- # dictionaries
- # myDict[key] # retrieve the value for that key
- # myDict[key] = value # assign a value to that key
- #for _key_ in myDict: # loop var holds the KEY, whatever we name it
- 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:
- # print: Check out Episode KEY or 'VALUE'
- print("Check out Episode {} or '{}'!".format(key, bestOfXF[key])) # myDict[key] gets the value
- # range()
- # the RANGE object and just doing things some # of times
- for num in range(5): # range(0, 5)
- print(num)
- # looping over a list but interested in indices (that's when I use "i" as a var name)
- for i in range(len(myList)):
- print("{}: {}".format(i, myList[i]))
- # Student question: Can you use help() and dir() in C859 v4/D335 OA?
- # Yes! They're built-in functions and part of Python
- # help(str)
- # print(dir(str))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement