Advertisement
jspill

webinar-for-loops-2024-02-02

Feb 3rd, 2024
943
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.20 KB | None | 0 0
  1. # # 2024 Feb 03
  2. # # WEBINAR: For Loops
  3. #
  4. # # We use loops to repeat actions
  5. # a WHILE loop... is an IF that repeats as long as the loop condition remains True
  6.  
  7. # FOR LOOPS are used for repeating actions for every element in a container (list, dict, tuple, str)
  8.  
  9. # Basic syntax of a for loop
  10. # for ___ in __someContainer__:
  11.  
  12. # list
  13. myList = ["Agent Scully", "Agent Mulder", "Walter Skinner", "CSM", "Mr. X"]
  14. for item in myList:
  15.     print(item)
  16.  
  17. # tuple
  18. myTuple = ("Gilligan", "Castaway002", "red", "crew")
  19. for item in myTuple:
  20.     print(item)
  21.  
  22. # string
  23. # myString = "It was the best of times."
  24. # for char in myString:
  25. #     print(char)
  26.  
  27. # dict
  28. # myDict = {
  29. #     key: value,
  30. #     key: value,
  31. #     key: value
  32. # }
  33. # myDict[key] # get the value for that key
  34. # myDict[key] = value # assign a value for that key
  35. bestOfXF = {
  36.     "1x00": "Pilot",
  37.     "2x10": "Red Museum",
  38.     "2x14": "Die Hand Die Verletzt",
  39.     "3x04": "Clyde Bruckman's Final Repose",
  40.     "3x12": "War of the Coprophages",
  41.     "3x20": "Jose Chung's From Outer Space",
  42.     "4x05": "The Field Where I Died",
  43.     "5x05": "The Post Modern Prometheus",
  44.     "5x17": "All Souls"
  45. }
  46. for key in bestOfXF:
  47.     # key is key
  48.     # bestOfXF[key] is its value
  49.     # value = bestOfXF[key] # if you like
  50.     # "Check out Episode ___ or '___'"
  51.     print(f"Check out Episode {key} or '{bestOfXF[key]}'")
  52.  
  53. # looping a known number of times
  54. # RANGE
  55. # range(start=0, stop, step=1)
  56. for num in range(0, 5): # [0, 1, 2, 3, 4]
  57.     print(num)
  58.  
  59.  
  60. # Need to know index? Range of length
  61. myList.append("Krycek")
  62. myList.append("Queequeg")
  63. myList.append("Frohicke")
  64. for i in range(0, len(myList)):
  65.     print(f"{i} is {myList[i]}")
  66.  
  67. # process in pairs
  68. for i in range(0, len(myList), 2):
  69.     print(f"{myList[i]} hates {myList[i+1]}")
  70.  
  71. # another way to loop focused on the index
  72. for i, item in enumerate(myList):
  73.     print(f"{i} --> {item}")
  74.  
  75.  
  76. # Common Pattern
  77. # "fill the basket"
  78.  
  79. # make a new container from previous one
  80. newList = [] # start with empty new container
  81. for item in myList:
  82.     # filter!
  83.     # if item[0] == "a" or item[0] == "A":
  84.     if item.lower().startswith("a"):
  85.         newList.append(item)
  86. print(newList)
  87.  
  88.  
  89.  
  90.  
  91.  
  92.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement