Advertisement
jspill

webinar-for-loops-2022-06-22

Jun 11th, 2022
1,360
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.21 KB | None | 0 0
  1. # 2022 June 11
  2. # WEBINAR: For Loops
  3. # We use loops to repeat actions
  4.  
  5. # a WHILE loop... btw.. is basically an IF statement
  6. # that repeats as long as its condition is true
  7.  
  8. # FOR LOOPS are used for repeating actions for every element
  9. # in a container like a list, string, tuple, etc...
  10.  
  11. # Basic syntax of a for loop
  12. # for ___ in __someContainer__:
  13. myList = ["Agent Scully", "Agent Mulder", "Walter Skinner", "CSM", "Mr. X"]
  14. for item in myList:
  15.     print(item)
  16.  
  17. # if you ever override the end param of print() btw...
  18. for item in myList:
  19.     print(item, end=" ")
  20. print() # start a clean line afterward
  21.  
  22. myTuple = ("Gilligan", "Castaway002", "red", "crew")
  23. for item in myTuple:
  24.     print(item)
  25.  
  26. scoobiesDCT = {
  27.     "Scooby": "a blue collar",
  28.     "Shaggy": "green",
  29.     "Velma": "orange",
  30.     "Daphne": "purple",
  31.     "Fred": "an ascot"
  32. }
  33. for key in scoobiesDCT: # loop var holds the key, regardless of the name
  34.     # myDictionary[key] # retrieve the value for that key
  35.     # myDictionary[key] = new value for that key
  36.     value = scoobiesDCT[key]
  37.     print("{} wears {}.".format(key, value))
  38.  
  39.  
  40. #print(scoobiesDCT.items())
  41. for k, v in scoobiesDCT.items():
  42.     print("{} still wears {}.".format(k, v))
  43.  
  44. myString = "In a hole in the ground there lived a Hobbit..."
  45. for char in myString:
  46.     print(char, end="-")
  47. print()
  48.  
  49. print(dir(str))
  50. # know your WHITESPACE
  51. # " " # the space you get from the spacebar
  52. "\n"
  53. "\t"
  54. "\r"
  55. "\b"
  56. "\f"
  57. "\v"
  58. # ... and then there's ~20 Unicode variations on a space
  59.  
  60. # just looping some number of times
  61. for n in range(5): # sorta like [0, 1, 2, 3, 4]
  62.     print(n)
  63.  
  64. for i in range(len(myList)):
  65.     print("{}: {}".format(i, myList[i]))
  66.  
  67.  
  68. # student questions
  69. print(", ".join(myList))
  70. print(", ".join(myTuple))
  71.  
  72. numList = [1, 2, 3, 4]
  73. numStrList = []
  74. for num in numList:
  75.     numStrList.append(str(num))
  76. print(numStrList) # ['1', '2', '3', '4']
  77. # print(", ".join(numList)) # error! Must be a container of strings, not integers!
  78. print(", ".join([str(num) for num in numList]))
  79.  
  80. numList = [5, 6, 7, 8]
  81. for i in range(len(numList)):
  82.     numList[i] = str(numList[i])
  83. print(numList) # ['5', '6', '7', '8']
  84. numTuple = tuple(numList)
  85. print(numTuple) # ('5', '6', '7', '8')
  86.  
  87.  
  88.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement