Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 2023 July 8
- # 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)
- #
- # # 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)
- #
- # # dictionaries
- # # { key: value, key:value}
- # # myDict[key] # retrieve the value for that key
- # # myDict[key] = value # assign 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(f"Check out Episode {key} or '{bestOfXF[key]}'")
- # to just to do something X number of times... range objects
- for num in range(7): # range(start, stop, step)... range(0, 7, 1) --> [0, 1, 2, 3, 4, 5, 6]
- print(num)
- myList = ["Agent Scully", "Agent Mulder", "Walter Skinner", "CSM", "Mr. X"]
- # if I need to know the index, then
- # for item/value in myList:
- for i in range(len(myList)):
- print(f"{i}: {myList[i]}")
- # could also use ENUMERATE
- for i, item in enumerate(myList):
- print("{} - {}".format(i, item))
- # STUDENT QUESTIONS
- # making dictionaries from lists... well that depends on what's in the list or lists you're starting with...
- # ... and what you want in the dictionary you're making
- # 1:1 Correspondence between lists... entries in one are keys and entries in other are their values
- myList = ["Agent Scully", "Agent Mulder", "Walter Skinner", "CSM", "Mr. X"]
- pets = ["Queequeg", "goldfish", "dog", "the human race", "cat"]
- petDict = {}
- for i in range(len(myList)):
- # myDict[key] = value
- petDict[myList[i]] = pets[i]
- print(petDict) # {'Agent Scully': 'Queequeg', 'Agent Mulder': 'goldfish', 'Walter Skinner': 'dog', 'CSM': 'the human race', 'Mr. X': 'cat'}
- # Alternating key, value data from one list
- anotherList = ["Agent Scully", "red ", " Agent Mulder", " gray", "Walter Skinner ", " white", "CSM", "\nblue", "Mr. X", "purple"]
- anotherDict = {}
- for i in range(0, len(anotherList), 2): # use the step
- # myDict[key] = value
- anotherDict[anotherList[i].strip()] = anotherList[i+1].strip()
- print(anotherDict) # {'Agent Scully': 'red', 'Agent Mulder': 'gray', 'Walter Skinner': 'white', 'CSM': 'blue', 'Mr. X': 'purple'}
- # Alternating key, value data from one list with potential repeat keys
- anotherList = ["Agent Scully", "red", " Agent Mulder", "gray", "Walter Skinner", "white", "CSM", "blue", "Mr. X", "purple", "CSM", "pink"]
- checkDict = {} # we'll check to see if the key is already there
- for i in range(0, len(anotherList), 2):
- if anotherList[i] in checkDict:
- # if it's there, add to it in some way...
- # value... "item1; item2"
- checkDict[anotherList[i]] += "; " + anotherList[i+1]
- else:
- checkDict[anotherList[i]] = anotherList[i + 1] # add if it's not there
- # print(checkDict) # {'Agent Scully': 'red', ' Agent Mulder': 'gray', 'Walter Skinner': 'white', 'CSM': 'blue; pink', 'Mr. X': 'purple'}
- # Student question Lab 14.10
- # one approach...
- # TODO: Declare any necessary variables here.
- filename = input()
- lastNames = []
- firstNames = []
- mid1 = []
- mid2 = []
- finals = []
- # TODO: Read a file name from the user and read the tsv file here.
- import csv
- with open(filename, "r") as f:
- contents = list(csv.reader(f, delimiter="\t"))
- # print(contents) # sometimes it helps to just print something and look at it
- for line in contents:
- lastNames.append(line[0])
- firstNames.append(line[1])
- mid1.append(int(line[2]))
- mid2.append(int(line[3]))
- finals.append(int(line[4]))
- # TODO: Compute student grades and exam averages, then output results to a text file here.
- with open("report.txt", "w") as f:
- for i in range(len(lastNames)): # we're using corresponding indices again
- gradesList = [mid1[i], mid2[i], finals[i]]
- avg = sum(gradesList) / len(gradesList)
- if avg >= 90:
- ltr = "A"
- elif avg >= 80:
- ltr = "B"
- elif avg >= 70:
- ltr = "C"
- elif avg >= 60:
- ltr = "D"
- else:
- ltr = "F"
- # that contents var based on the original file is still around! Let's use it...
- f.write("\t".join(contents[i]) + f"\t{ltr}\n") # part of the loop
- # NOT part of the loop!
- f.write(f"\nAverages: midterm1 {sum(mid1) / len(mid1):.2f}, midterm2 {sum(mid2) / len(mid2):.2f}, final {sum(finals) / len(finals):.2f}\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement