Advertisement
jspill

webinar-for-loops-2023-09-09

Sep 9th, 2023
1,471
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.93 KB | None | 0 0
  1. # 2023 Sept 9
  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. # tuple
  19. myTuple = ("Gilligan", "Castaway002", "red", "crew")
  20. for item in myTuple:
  21.     print(item)
  22.  
  23. # string
  24. myString = "It was the best\n of times."
  25. for char in myString:
  26.     # print(char)
  27.     # print(f"{char} is alphabetical? {char.isalpha()}")
  28.     print(f"{char} is a kind of whitespace? {char.isspace()}")
  29.  
  30. # dictionaries
  31. # {key:value, key:value}
  32. # myDict[key] # retrieve the value for that key
  33. # myDict[key] = value # assign a value for that key
  34.  
  35. # for _key_ in myDict:
  36. bestOfXF = {
  37.     "1x00": "Pilot",
  38.     "2x10": "Red Museum",
  39.     "2x14": "Die Hand Die Verletzt",
  40.     "3x04": "Clyde Bruckman's Final Repose",
  41.     "3x12": "War of the Coprophages",
  42.     "3x20": "Jose Chung's From Outer Space",
  43.     "4x05": "The Field Where I Died",
  44.     "5x05": "The Post Modern Prometheus",
  45.     "5x17": "All Souls"
  46. }
  47.  
  48. for key in bestOfXF:
  49.     # "Check out Episode ___ or '___'"
  50.     # var key holds each key as I loop
  51.     # corresponding value is bestOfXF[key]
  52.     val = bestOfXF[key]
  53.     # print(f"Check out Episode {key} or '{bestOfXF[key]}'")
  54.     print(f"Check out Episode {key} or '{val}'")
  55.  
  56. # range()... a range object, which we use to loop a number of times
  57. for num in range(0, 5): # --> [0, 1, 2, 3, 4]
  58.     print(num)
  59.  
  60. # using range() to correspond to index
  61. for i in range(len(myList)):
  62.     print(f"Position {i} is: {myList[i]}")
  63.  
  64. # or... use enumerate() to get index and value
  65. for i, item in enumerate(myList):
  66.     print(f"Position {i} is --> {item}")
  67.  
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement