Advertisement
jspill

webinar-for-loops-2024-01-06

Jan 6th, 2024
1,061
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.96 KB | None | 0 0
  1. # 2024 Jan 06
  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) # print(item, end="\n")
  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, end="")
  26. print()
  27. # fill the basket pattern
  28. # newList = []
  29. # newString = ""
  30. # for item in myList:
  31. #     if item.startswith("Agent"):
  32. #         #newList.append(item)
  33. #         # newString = newString + item
  34. #         newString += item + " "
  35. # print(newString)
  36.  
  37. # myDict = {
  38. #     key: value,
  39. #     key: value,
  40. #     key: value
  41. # }
  42. # myDict[key]
  43. # myDict[key] = value
  44. bestOfXF = {
  45.     "1x00": "Pilot",
  46.     "2x10": "Red Museum",
  47.     "2x14": "Die Hand Die Verletzt",
  48.     "3x04": "Clyde Bruckman's Final Repose",
  49.     "3x12": "War of the Coprophages",
  50.     "3x20": "Jose Chung's From Outer Space",
  51.     "4x05": "The Field Where I Died",
  52.     "5x05": "The Post Modern Prometheus",
  53.     "5x17": "All Souls"
  54. }
  55. for key in bestOfXF:
  56.     # print(key) # value for that key is bestOfXF[key]
  57.     # "Check out Episode ___ or '___'"
  58.     print(f"Check out Episode {key} or '{bestOfXF[key]}'")
  59.  
  60. # looping a known number of times
  61. # RANGE
  62. # range(start, stop, step)
  63. # for n in range(0, 5): # --> [0, 1, 2, 3, 4]
  64. #     print(n)
  65. myList.append("Krycek")
  66. # if I'm interested in index
  67. for i in range(0, len(myList)):
  68.     # print(i)
  69.     # print(myList[i])
  70.     print(f"Position {i} is {myList[i]}")
  71.  
  72. # or... use enumerate() to get index and value
  73. for i, item in enumerate(myList):
  74.     print(f"Position {i} is still {item}")
  75.  
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement