Advertisement
jspill

webinar-python-for-loops-2022-07-16

Jul 16th, 2022
1,112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.02 KB | None | 0 0
  1. # 2022 July 16
  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.  
  14. myList = ["Agent Scully", "Agent Mulder", "Walter Skinner", "CSM", "Mr. X"]
  15. for item in myList:
  16.     print(item)
  17.  
  18. myTuple = ("Gilligan", "Castaway002", "red", "crew")
  19. for item in myTuple:
  20.     print(item)
  21.  
  22. myString = "It was the best of times. It was the worst of times."
  23. # for char in myString:
  24. #     print(char)
  25. for char in myString:
  26.     print(char, end="-") # end="\n"
  27. print() # best practice... always end with a clean line, see Ch 2.9
  28. print("Something new...")
  29.  
  30. scoobiesDCT = {
  31.     "Scooby": "a blue collar",
  32.     "Shaggy": "green",
  33.     "Velma": "orange",
  34.     "Daphne": "purple",
  35.     "Fred": "an ascot"
  36. }
  37.  
  38. # myDictionary[key] # retrieve the value for that key
  39. # myDictionary[key] = value # set a new value for that key
  40. # for ___ in scoobiesDCT: # loop var hold the KEY, whatever we name it
  41. for key in scoobiesDCT:
  42.     print("{} wears {}.".format(key, scoobiesDCT[key]))
  43.  
  44. for key in scoobiesDCT:
  45.     v = scoobiesDCT[key]
  46.     print("{} wears {}.".format(key, v))
  47.  
  48. for k, v in scoobiesDCT.items():
  49.     print("{} still wears {}.".format(k, v))
  50.  
  51. # just looping some number of times
  52. for n in range(5): # [0, 1, 2, 3, 4]
  53.     print(n)
  54.  
  55. # going directly over list values
  56. # for item in myList:
  57.  
  58. # What I'm interested in INDEX of the VALUES?
  59. for i in range(len(myList)):
  60.     print("{} --> {}".format(i, myList[i]))
  61.  
  62. # similar to using enumerate()
  63. for i, item in enumerate(myList):
  64.     print("{} ----> {}".format(i, item))
  65.  
  66.  
  67. # Is a value in a container?
  68. # You DON'T need to loop for that
  69. # if _value_ in _container_:
  70. print("Agent Scully" in myList)
  71. print("Krycek" in myList)
  72.  
  73. print("Scooby" in scoobiesDCT)
  74. print("orange" in scoobiesDCT) # values aren't checked!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement