Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 2022 Feb5
- # 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...
- myList = ["Agent Scully", "Agent Mulder", "Walter Skinner", "CSM", "Mr. X"]
- # for __ in ___:
- for item in myList:
- print(item)
- myTuple = ("Gilligan", "Castaway002", "red", "crew")
- for item in myTuple:
- print(item)
- myString = "Just sit right back and you'll hear a tale."
- for char in myString:
- print(char, end="-") # whenever you override end parameter of print()...
- # print("the next thing")
- print() # get a clean line... see Ch 2.9
- print("the next thing")
- # looping over dictionaries
- scoobiesDCT = {
- "Scooby": "a blue collar",
- "Shaggy": "green",
- "Velma": "orange",
- "Daphne": "purple",
- "Fred": "an ascot"
- }
- for key in scoobiesDCT: # for loop var with dicts is the KEY
- print(f"{key} wears {scoobiesDCT[key]}.")
- # f string... same as....
- # print("{} wears {}.".format(key, scoobiesDCT[key]))
- # myDictionary[someKey] --> retrieve the value for that key
- # myDictionary[someKey] = value
- # range()
- for n in range(0, 5):
- print(f"{n} hey")
- # using range() to look at index of list items
- myList.append("Krycek")
- for i in range(0, len(myList)):
- print("{}: {}".format(i, myList[i]))
- # # could do same with enumerate()
- # for i, item in enumerate(myTuple):
- # print("{}: {}".format(i, myTuple[i]))
- numList = [0, 1, 2, 3, 4] # 0 -> 1 -> 2 -> 3 -> 4
- for i in range(0, len(numList)):
- if i < len(numList) - 1:
- print("{} ->".format(i), end=" ") # most of time, but not on the last
- else:
- print(i)
- # print() # print on else above makes this unnecessary
- # We use for loops when looping over line by line data from files...
- # I have a CSV file named "mock_data.csv"
- with open("mock_data.csv", "r") as f:
- # read() --> returns whole file as one big str
- # readlines() --> returns you a line by line list of strings
- # print(f.readlines()) # you'll see all those \n returns in each string
- for line in f.readlines():
- # print(type(line))
- # print(line)
- # myInputVar = input().rstrip()
- line = line.rstrip()
- # print(line.split(","))
- lineList = line.split(",")
- # print(lineList[1]) # first names
- print("{}'s email is {}.".format(lineList[1], lineList[3]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement