Advertisement
jspill

webinar-for-loops-2021-06-05

Jun 5th, 2021
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.20 KB | None | 0 0
  1. # WEBINAR: for loops
  2.  
  3. # We use loops to repeat actions
  4. # a WHILE loop is basically an IF statement
  5. # that repeats as long as its condition is true
  6.  
  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 LOOP syntax with a list
  12. myList = ["Agent Scully", "Agent Mulder", "Walter Skinner", "CSM", "Mr. X"] # X-Files characters
  13. for item in myList:
  14.     print(item)
  15.  
  16. myTuple = ("Gilligan", "Castaway002", "red", "crew") # things about Gilligan
  17. for item in myTuple:
  18.     print(item)
  19.  
  20. myString = "Just sit right back and you'll hear a tale."
  21. # for char in myString:
  22. #     print(char)
  23.  
  24. scoobies = {
  25.     "Scooby": "a blue collar",
  26.     "Shaggy": "green",
  27.     "Velma": "orange",
  28.     "Daphne": "purple",
  29.     "Fred": "an ascot"
  30. }
  31. for key in scoobies: # loop var for a dictionary is the KEY
  32.     # someDictionary[someKey] --> retrieve the value for the key
  33.     print(key, "-", scoobies[key])
  34.  
  35. # if you REALLY want a var for key and value
  36. for k, v in scoobies.items():
  37.     print(k, "-->", v)
  38.     print(k, "------>", scoobies[k])
  39.  
  40. # if you're as interested in the INDEX position as you the ITEM/VALUE
  41. for i, item in enumerate(myList):
  42.     # print(i, item)
  43.     print(i, myList[i])
  44.  
  45. for n in range(0, 5):
  46.     print(n)
  47.  
  48. for i in range(len(myString)):
  49.     print(i, myString[i])
  50.  
  51.  
  52. # Complete the function to return the number of upper case letters in the given string
  53. def countUpper(mystring):
  54.     # string class method: .isupper()
  55.     count = 0
  56.     for char in mystring:
  57.         if char.isupper():
  58.             count += 1
  59.     return count
  60.  
  61. print(countUpper('Welcome to WGU')) # 4
  62. print(countUpper('Hello Mary')) # 2
  63.  
  64. print("--- 25's in 1 to 100:")
  65. count = 0 # if you're "accumulating" or "filling the basket" create those vars BEFORE the loop...
  66. numList = []
  67. for num in range(1, 101):
  68.     if num % 25 == 0:
  69.         print(num)
  70.         numList.append(num) # ... then add to them within the loop...
  71.         count += 1
  72. print(count)  # and remember they're not done until the loop is over (back one level of indentation)
  73. print(numList)
  74.  
  75.  
  76. print("--- 37's in 1 to 10000:")
  77. for num in range(1, 10001):
  78.     if num % 43 == 0:
  79.         print(num)
  80.  
  81.  
  82.  
  83.  
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement