Advertisement
jspill

webinar-for-loops-2022-12-03

Dec 3rd, 2022
736
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.15 KB | None | 0 0
  1. # 2022 Dec 3
  2.  
  3. # WEBINAR: For Loops
  4.  
  5. # We use loops to repeat actions
  6.  
  7. # a WHILE loop... btw.. is basically an IF statement
  8. # that repeats as long as its condition is true
  9.  
  10. # FOR LOOPS are used for repeating actions for every element
  11. # in a container like a list, string, tuple, etc...
  12.  
  13. # Basic syntax of a for loop
  14. # for _something_ in _someContainer__:
  15.  
  16. # list
  17. myList = ["Agent Scully", "Agent Mulder", "Walter Skinner", "CSM", "Mr. X"]
  18. for item in myList:
  19.     print(item)
  20.  
  21. # tuples
  22. myTuple = ("Gilligan", "Castaway002", "red", "crew")
  23. for item in myTuple:
  24.     print(item)
  25.  
  26. # strings
  27. myString = "It was the best of times. \nIt was the\t worst of times."
  28. for char in myString:
  29.     print(char, end="") # print(end="\n")
  30. print()
  31. # test to see if you have a clean new line
  32. # print("A clean new line.")
  33.  
  34. # dictionaries
  35. bestOfXF = {
  36.     "1x00": "Pilot",
  37.     "2x10": "Red Museum",
  38.     "2x14": "Die Hand Die Verletzt",
  39.     "3x04": "Clyde Bruckman's Final Repose",
  40.     "3x12": "War of the Coprophages",
  41.     "3x20": "Jose Chung's From Outer Space",
  42.     "4x05": "The Field Where I Died",
  43.     "5x05": "The Post Modern Prometheus",
  44.     "5x17": "All Souls"
  45. }
  46. # myDict[key] # retrieve the value for that key
  47. # myDict[key] = value # assign a value to that key
  48.  
  49. for key in bestOfXF: # for key in nameOfDict:
  50.     # print: Check out Episode KEY or 'VALUE'
  51.     value = bestOfXF[key]
  52.     print("Check out Episode {} or '{}'".format(key, value))
  53.  
  54. # range()
  55. for num in range(0, 5): # [0, 1, 2, 3, 4]
  56.     print(num)
  57.  
  58. # range() of len()
  59. for i in range(len(myList)):
  60.     print("{} - {}".format(i, myList[i]))
  61.  
  62. # while loops
  63. # any variables needed in the loop condition must be created outside (they're not tied to the loop itself like a for loop var is)
  64. # x = int(input()) # 0
  65. # # if x < 3:
  66. # #     print(x)
  67. # while x < 3: # has a condition, just like an if statement
  68. #     print(x)
  69. #     x += 1 # the loop variable (or something in the loop condition) must change with each iteration
  70.  
  71. # nested loops
  72. for n in range(3):
  73.     for m in range(4): # entire inner loop iterates for every one interation of outer loop
  74.         print(f"{n}-{m}")
  75.  
  76.  
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
  83.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement