Advertisement
jspill

webinar-for-loops-2023-03-04

Mar 4th, 2023
604
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.11 KB | None | 0 0
  1. # 2023 Feb 4
  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
  9. # in a container like a list, string, tuple, etc...
  10.  
  11. # Basic syntax of a for loop
  12. # for __someVar__ in __someContainer__:
  13.  
  14. # list
  15. myList = ["Agent Scully", "Agent Mulder", "Walter Skinner", "CSM", "Mr. X"]
  16. for item in myList:
  17.     print(item)
  18.  
  19. # tuples
  20. myTuple = ("Gilligan", "Castaway002", "red", "crew")
  21. for item in myTuple:
  22.     print(item)
  23.  
  24. # strings
  25. myString = "It was the best of times."
  26. # for char in myString:
  27. #     print(char) # print(char, end="\n")
  28.  
  29. # printing on the same line... overriding the end parameter of print()
  30. for char in myString:
  31.     print(char, end="-")
  32. print() # get the new line back
  33. # print("I want this on a new line.") # good way to check yourself
  34.  
  35. # dictionaries
  36. # myDict = {"key": "value"}
  37. bestOfXF = {
  38.     "1x00": "Pilot",
  39.     "2x10": "Red Museum",
  40.     "2x14": "Die Hand Die Verletzt",
  41.     "3x04": "Clyde Bruckman's Final Repose",
  42.     "3x12": "War of the Coprophages",
  43.     "3x20": "Jose Chung's From Outer Space",
  44.     "4x05": "The Field Where I Died",
  45.     "5x05": "The Post Modern Prometheus",
  46.     "5x17": "All Souls"
  47. }
  48. # myDict[key] # retrieves the value associated with the key
  49. # bestOfXF["1x00"] # "Pilot"
  50. # # myDict[key] = value # assign a value to that key
  51. for key in bestOfXF:
  52.     print("Check out Episode {} or '{}'".format(key, bestOfXF[key]))
  53.  
  54. # range()
  55. for num in range(0, 5): # [0, 1, 2, 3, 4]
  56.     print(num)
  57.  
  58. # range() of len()
  59. myList.append("Queequeg")
  60. for i in range(0, len(myList)):
  61.     print("{} - {}".format(i, myList[i]))
  62.  
  63.  
  64. # Student Questions
  65.  
  66. # nested loops
  67. # inner loop cycles completes in entirety once PER every cylce of outer loop, like multiplication...
  68. # one of these for every one of those
  69. rows = [1, 2, 3]
  70. cols = ["a", "b", "c", "d", "e"]
  71.  
  72. for r in rows:
  73.     for c in cols:
  74.         print("{}-{}".format(r, c))
  75. # 1-a
  76. # 1-b
  77. # 1-c
  78. # 1-d
  79. # 1-e
  80. # 2-a
  81. # 2-b
  82. # 2-c
  83. # 2-d
  84. # 2-e
  85. # 3-a
  86. # 3-b
  87. # 3-c
  88. # 3-d
  89. # 3-e
  90.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement