Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 2022 June 11
- # 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)
- # if you ever override the end param of print() btw...
- for item in myList:
- print(item, end=" ")
- print() # start a clean line afterward
- myTuple = ("Gilligan", "Castaway002", "red", "crew")
- for item in myTuple:
- print(item)
- scoobiesDCT = {
- "Scooby": "a blue collar",
- "Shaggy": "green",
- "Velma": "orange",
- "Daphne": "purple",
- "Fred": "an ascot"
- }
- for key in scoobiesDCT: # loop var holds the key, regardless of the name
- # myDictionary[key] # retrieve the value for that key
- # myDictionary[key] = new value for that key
- value = scoobiesDCT[key]
- print("{} wears {}.".format(key, value))
- #print(scoobiesDCT.items())
- for k, v in scoobiesDCT.items():
- print("{} still wears {}.".format(k, v))
- myString = "In a hole in the ground there lived a Hobbit..."
- for char in myString:
- print(char, end="-")
- print()
- print(dir(str))
- # know your WHITESPACE
- # " " # the space you get from the spacebar
- "\n"
- "\t"
- "\r"
- "\b"
- "\f"
- "\v"
- # ... and then there's ~20 Unicode variations on a space
- # just looping some number of times
- for n in range(5): # sorta like [0, 1, 2, 3, 4]
- print(n)
- for i in range(len(myList)):
- print("{}: {}".format(i, myList[i]))
- # student questions
- print(", ".join(myList))
- print(", ".join(myTuple))
- numList = [1, 2, 3, 4]
- numStrList = []
- for num in numList:
- numStrList.append(str(num))
- print(numStrList) # ['1', '2', '3', '4']
- # print(", ".join(numList)) # error! Must be a container of strings, not integers!
- print(", ".join([str(num) for num in numList]))
- numList = [5, 6, 7, 8]
- for i in range(len(numList)):
- numList[i] = str(numList[i])
- print(numList) # ['5', '6', '7', '8']
- numTuple = tuple(numList)
- print(numTuple) # ('5', '6', '7', '8')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement