Advertisement
jspill

webinar-for-loops-2023-07-08

Jul 8th, 2023
845
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.11 KB | None | 1 0
  1. # 2023 July 8
  2. # WEBINAR: For Loops
  3.  
  4. # We use loops to repeat actions
  5.  
  6. # a WHILE loop... is an IF that repeats as long as the loop condition remains True
  7.  
  8. # FOR LOOPS are used for repeating actions for every element in a container (list, str, tuples, sets, dictionary, range objects)
  9.  
  10. # Basic syntax of a for loop
  11. # for ___ in _someContainer_:
  12.  
  13. # list
  14. # myList = ["Agent Scully", "Agent Mulder", "Walter Skinner", "CSM", "Mr. X"]
  15. # for item in myList:
  16. #     print(item)
  17. #
  18. # # tuples
  19. # myTuple = ("Gilligan", "Castaway002", "red", "crew")
  20. # for item in myTuple:
  21. #     print(item)
  22. #
  23. # # strings
  24. # myString = "It was the best of times."
  25. # for char in myString:
  26. #     print(char)
  27. #
  28. # # dictionaries
  29. # # { key: value, key:value}
  30. # # myDict[key] # retrieve the value for that key
  31. # # myDict[key] = value # assign value to key
  32. # bestOfXF = {
  33. #     "1x00": "Pilot",
  34. #     "2x10": "Red Museum",
  35. #     "2x14": "Die Hand Die Verletzt",
  36. #     "3x04": "Clyde Bruckman's Final Repose",
  37. #     "3x12": "War of the Coprophages",
  38. #     "3x20": "Jose Chung's From Outer Space",
  39. #     "4x05": "The Field Where I Died",
  40. #     "5x05": "The Post Modern Prometheus",
  41. #     "5x17": "All Souls"
  42. # }
  43. # for key in bestOfXF:
  44. #     # "Check out Episode ___ or '___'"
  45. #     print(f"Check out Episode {key} or '{bestOfXF[key]}'")
  46.  
  47. # to just to do something X number of times... range objects
  48. for num in range(7): # range(start, stop, step)... range(0, 7, 1) --> [0, 1, 2, 3, 4, 5, 6]
  49.     print(num)
  50.  
  51. myList = ["Agent Scully", "Agent Mulder", "Walter Skinner", "CSM", "Mr. X"]
  52. # if I need to know the index, then
  53. # for item/value in myList:
  54. for i in range(len(myList)):
  55.     print(f"{i}: {myList[i]}")
  56.  
  57. # could also use ENUMERATE
  58. for i, item in enumerate(myList):
  59.     print("{} - {}".format(i, item))
  60.  
  61.  
  62.  
  63. # STUDENT QUESTIONS
  64. # making dictionaries from lists... well that depends on what's in the list or lists you're starting with...
  65. # ... and what you want in the dictionary you're making
  66.  
  67. # 1:1 Correspondence between lists... entries in one are keys and entries in other are their values
  68. myList = ["Agent Scully", "Agent Mulder", "Walter Skinner", "CSM", "Mr. X"]
  69. pets = ["Queequeg", "goldfish", "dog", "the human race", "cat"]
  70.  
  71.  
  72. petDict = {}
  73. for i in range(len(myList)):
  74.     # myDict[key] = value
  75.     petDict[myList[i]] = pets[i]
  76. print(petDict) # {'Agent Scully': 'Queequeg', 'Agent Mulder': 'goldfish', 'Walter Skinner': 'dog', 'CSM': 'the human race', 'Mr. X': 'cat'}
  77.  
  78.  
  79. # Alternating key, value data from one list
  80. anotherList = ["Agent Scully", "red ", " Agent Mulder", " gray", "Walter Skinner ", "  white", "CSM", "\nblue", "Mr. X", "purple"]
  81. anotherDict = {}
  82. for i in range(0, len(anotherList), 2): # use the step
  83.     # myDict[key] = value
  84.     anotherDict[anotherList[i].strip()] = anotherList[i+1].strip()
  85. print(anotherDict) # {'Agent Scully': 'red', 'Agent Mulder': 'gray', 'Walter Skinner': 'white', 'CSM': 'blue', 'Mr. X': 'purple'}
  86.  
  87.  
  88. # Alternating key, value data from one list with potential repeat keys
  89. anotherList = ["Agent Scully", "red", " Agent Mulder", "gray", "Walter Skinner", "white", "CSM", "blue", "Mr. X", "purple", "CSM", "pink"]
  90. checkDict = {} # we'll check to see if the key is already there
  91. for i in range(0, len(anotherList), 2):
  92.     if anotherList[i] in checkDict:
  93.         # if it's there, add to it in some way...
  94.         # value... "item1; item2"
  95.         checkDict[anotherList[i]] += "; " + anotherList[i+1]
  96.     else:
  97.         checkDict[anotherList[i]] = anotherList[i + 1] # add if it's not there
  98. # print(checkDict) # {'Agent Scully': 'red', ' Agent Mulder': 'gray', 'Walter Skinner': 'white', 'CSM': 'blue; pink', 'Mr. X': 'purple'}
  99.  
  100.  
  101.  
  102. # Student question Lab 14.10
  103. # one approach...
  104.  
  105. # TODO: Declare any necessary variables here.
  106. filename = input()
  107. lastNames = []
  108. firstNames = []
  109. mid1 = []
  110. mid2 = []
  111. finals = []
  112.  
  113. # TODO: Read a file name from the user and read the tsv file here.
  114. import csv
  115.  
  116. with open(filename, "r") as f:
  117.     contents = list(csv.reader(f, delimiter="\t"))
  118. # print(contents) # sometimes it helps to just print something and look at it
  119. for line in contents:
  120.     lastNames.append(line[0])
  121.     firstNames.append(line[1])
  122.     mid1.append(int(line[2]))
  123.     mid2.append(int(line[3]))
  124.     finals.append(int(line[4]))
  125.  
  126. # TODO: Compute student grades and exam averages, then output results to a text file here.
  127. with open("report.txt", "w") as f:
  128.     for i in range(len(lastNames)): # we're using corresponding indices again
  129.         gradesList = [mid1[i], mid2[i], finals[i]]
  130.         avg = sum(gradesList) / len(gradesList)
  131.         if avg >= 90:
  132.             ltr = "A"
  133.         elif avg >= 80:
  134.             ltr = "B"
  135.         elif avg >= 70:
  136.             ltr = "C"
  137.         elif avg >= 60:
  138.             ltr = "D"
  139.         else:
  140.             ltr = "F"
  141.         # that contents var based on the original file is still around! Let's use it...
  142.         f.write("\t".join(contents[i]) + f"\t{ltr}\n") # part of the loop
  143.     # NOT part of the loop!
  144.     f.write(f"\nAverages: midterm1 {sum(mid1) / len(mid1):.2f}, midterm2 {sum(mid2) / len(mid2):.2f}, final {sum(finals) / len(finals):.2f}\n")
  145.  
  146.  
  147.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement