Advertisement
jspill

webinar-for-loops-2023-02-04

Feb 4th, 2023
1,079
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | None | 0 0
  1. # 2023 Feb 4
  2. # WEBINAR: For Loops
  3.  
  4. # We use loops to repeat actions
  5.  
  6. # a WHILE loop... btw.. is basically an IF statement
  7. # that repeats as long as its condition is true
  8.  
  9. # FOR LOOPS are used for repeating actions for every element
  10. # in a container like a list, string, tuple, etc...
  11.  
  12. # Basic syntax of a for loop
  13. # for __someVar__ in __someContainer__:
  14.  
  15. # list
  16. myList = ["Agent Scully", "Agent Mulder", "Walter Skinner", "CSM", "Mr. X"]
  17. for item in myList:
  18.     print(item) # print(item, end="\n")
  19.  
  20. # tuples
  21. myTuple = ("Gilligan", "Castaway002", "red", "crew")
  22. for item in myTuple:
  23.     print(item)
  24.  
  25. # strings
  26. myString = "It was the best of times."
  27. for char in myString:
  28.     print(char)
  29.  
  30. # printing on the same line... overriding the end parameter of print()
  31. for char in myString:
  32.     print(char, end="-")
  33. print() # get the new line back
  34. # print("I want this on a new line.") # good way to check yourself
  35.  
  36. # dictionaries
  37. # myDict = {"key": "value"}
  38. bestOfXF = {
  39.     "1x00": "Pilot",
  40.     "2x10": "Red Museum",
  41.     "2x14": "Die Hand Die Verletzt",
  42.     "3x04": "Clyde Bruckman's Final Repose",
  43.     "3x12": "War of the Coprophages",
  44.     "3x20": "Jose Chung's From Outer Space",
  45.     "4x05": "The Field Where I Died",
  46.     "5x05": "The Post Modern Prometheus",
  47.     "5x17": "All Souls"
  48. }
  49. # myDict[key] # retrieve the value associated with that key
  50. # myDict[key] = value # assign a value to that key
  51. for key in bestOfXF:
  52.     # "Check out Episode --- or '---'"
  53.     # val = bestOfXF[key]
  54.     print("Check out Episode {} or '{}'".format(key, bestOfXF[key]))
  55.  
  56. # range()
  57. for num in range(0, 5): # [0, 1, 2, 3, 4]
  58.     print(num)
  59.  
  60. # range() of len() of list
  61. myList.append("Queequeg")
  62. for i in range(0, len(myList)):
  63.     print("{} - {}".format(i, myList[i]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement