Advertisement
jspill

webinar-for-loops-2023-08-05

Aug 5th, 2023
1,220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.79 KB | None | 0 0
  1. # 2023 Aug 5
  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) # print(item, end="\n")
  17.  
  18. # tuple
  19. myTuple = ("Gilligan", "Castaway002", "red", "crew")
  20. for item in myTuple:
  21.     print(item)
  22.  
  23. # string
  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] # retrive the value for that key
  31. # myDict[key] = value # assign a value to that key
  32.  
  33. # for key in myDict: # loop var holds the keys, regardless of what I call it
  34. bestOfXF = {
  35.     "1x00": "Pilot",
  36.     "2x10": "Red Museum",
  37.     "2x14": "Die Hand Die Verletzt",
  38.     "3x04": "Clyde Bruckman's Final Repose",
  39.     "3x12": "War of the Coprophages",
  40.     "3x20": "Jose Chung's From Outer Space",
  41.     "4x05": "The Field Where I Died",
  42.     "5x05": "The Post Modern Prometheus",
  43.     "5x17": "All Souls"
  44. }
  45. # for key in bestOfXF:
  46. #     # "Check out Episode ___ or '___'"
  47. #     val = bestOfXF[key]
  48. #     print(f"Check out Episode {key} or '{val}'")
  49.  
  50. # range()... just to repeat a number of times
  51. for num in range(0, 5): # range(start, stop, step) --> [0, 1, 2, 3, 4]
  52.     print(num)
  53.  
  54. # going over a sequenced container and you need the INDEX
  55. # 2 choices
  56.  
  57. # range() of len()
  58. # for item in myList:
  59. for i in range(len(myList)):
  60.     # myList[i]
  61.     print(f"{i} - {myList[i]}")
  62.  
  63. # enumerate()
  64. for i, item in enumerate(myList):
  65.     print(f"{i} --> {item}")
  66.  
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement