Advertisement
jspill

webinar-for-loops-2022-08-13

Aug 13th, 2022
1,086
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.11 KB | None | 0 0
  1. # 2022 Aug 13
  2. # WEBINAR: For Loops
  3. # We use loops to repeat actions
  4.  
  5. # a WHILE loop... btw.. is basically an IF statement
  6. # that repeats as long as its condition is 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 ___ in __someContainer__:
  13.  
  14. myList = ["Agent Scully", "Agent Mulder", "Walter Skinner", "CSM", "Mr. X"]
  15. for item in myList:
  16.     print(item)
  17.  
  18. myTuple = ("Gilligan", "Castaway002", "red", "crew")
  19. for item in myTuple:
  20.     print(item)
  21.  
  22. myString = "It was the best of times. It was the worst of times."
  23. # for char in myString:
  24. #     print(char)
  25. for char in myString:
  26.     print(char, end="") # default end "\n"
  27. print() # ... just to get the default "\n"
  28. print("something else I needed to print")
  29.  
  30.  
  31. # help(str)
  32. # print(dir(str))
  33.  
  34. # check for whitespace
  35. for char in myString:
  36.     if not char.isspace():
  37.         print(char, end="")
  38. print()
  39.  
  40. # for loop over a dict
  41. bestOfXF = {
  42.     "1x00": "Pilot",
  43.     "2x10": "Red Museum",
  44.     "3x04": "Clyde Bruckman's Final Repose",
  45.     "3x12": "War of the Coprophages",
  46.     "3x20": "Jose Chung's From Outer Space",
  47.     "4x05": "The Field Where I Died",
  48.     "5x05": "The Post Modern Prometheus",
  49.     "5x17": "All Souls"
  50. }
  51. for key in bestOfXF: # loop var holds KEY
  52.     value = bestOfXF[key]
  53.     print(f"Check out Episode {key} or '{value}'!") # value is nameOfDict[key]
  54.  
  55. for k, v in bestOfXF.items():
  56.     print(f"Check out Episode {k}, which is called '{v}'!")  # value is nameOfDict[key]
  57.  
  58. # the RANGE object and just doing things some # of times
  59. for n in range(0, 7): # [0, 1, 2, 3, 4, 5, 6]
  60.     print(n)
  61.  
  62. # What I'm interested in INDEX of the VALUES in a list, etc?
  63. for i in range(len(myList)):
  64.     print(f"{i} --> {myList[i]}")
  65.  
  66.  
  67. # for i in range(len(myList)):
  68. #     print(f"{myList[i]} fought {myList[i+1]}!") # OUT OF RANGE the last time!
  69.  
  70. # so... when comparing THIS position i and NEXT position i, adjust range by 1...
  71. for i in range(len(myList)-1):
  72.     print(f"{myList[i]} fought {myList[i+1]}!")
  73.  
  74.  
  75.  
  76.  
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
  83.  
  84.  
  85.  
  86.  
  87.  
  88.  
  89.  
  90.  
  91.  
  92.  
  93.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement