Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 2022 July 16
- # 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)
- myTuple = ("Gilligan", "Castaway002", "red", "crew")
- for item in myTuple:
- print(item)
- myString = "It was the best of times. It was the worst of times."
- # for char in myString:
- # print(char)
- for char in myString:
- print(char, end="-") # end="\n"
- print() # best practice... always end with a clean line, see Ch 2.9
- print("Something new...")
- scoobiesDCT = {
- "Scooby": "a blue collar",
- "Shaggy": "green",
- "Velma": "orange",
- "Daphne": "purple",
- "Fred": "an ascot"
- }
- # myDictionary[key] # retrieve the value for that key
- # myDictionary[key] = value # set a new value for that key
- # for ___ in scoobiesDCT: # loop var hold the KEY, whatever we name it
- for key in scoobiesDCT:
- print("{} wears {}.".format(key, scoobiesDCT[key]))
- for key in scoobiesDCT:
- v = scoobiesDCT[key]
- print("{} wears {}.".format(key, v))
- for k, v in scoobiesDCT.items():
- print("{} still wears {}.".format(k, v))
- # just looping some number of times
- for n in range(5): # [0, 1, 2, 3, 4]
- print(n)
- # going directly over list values
- # for item in myList:
- # What I'm interested in INDEX of the VALUES?
- for i in range(len(myList)):
- print("{} --> {}".format(i, myList[i]))
- # similar to using enumerate()
- for i, item in enumerate(myList):
- print("{} ----> {}".format(i, item))
- # Is a value in a container?
- # You DON'T need to loop for that
- # if _value_ in _container_:
- print("Agent Scully" in myList)
- print("Krycek" in myList)
- print("Scooby" in scoobiesDCT)
- print("orange" in scoobiesDCT) # values aren't checked!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement