Advertisement
jspill

webinar-for-loops-2021-03-13

Mar 13th, 2021
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | None | 0 0
  1. # 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. # a FOR loop is more for repeating something a known
  8. # number of times, or doing something ONCE PER ITEM
  9. # in some iterable container: list, string, etc
  10.  
  11. # basic syntax of a FOR loop with a list
  12. myList = ["Gilligan", "Scooby", "Agent Scully"] # tv characters
  13. for item in myList:
  14.     print(item)
  15.  
  16. # or a tuple
  17. myTuple = ("Gilligan", "Castaway002", "red", "crew") # things about Gilligan
  18. for item in myTuple:
  19.     print(item)
  20.  
  21. # or a string, I'm only changing the loop variable name
  22. myString = "Just sit right back and we'll talk about Gilligan and company."
  23. # for char in myString:
  24. #     print(char)
  25.  
  26. # Note that looping over sets is exactly the same as those
  27. # ... even though sets have no order and thus no indexes,
  28. # you can still loop over them!
  29.  
  30.  
  31. scoobies = {
  32.     "Scooby": "a blue collar",
  33.     "Shaggy": "green",
  34.     "Velma": "orange",
  35.     "Daphne": "purple",
  36.     "Fred": "an ascot"
  37. }
  38. # 2 ways to iterate over a dictionary
  39. for key in scoobies:
  40.     # dictionaryName[key]
  41.     # myList[0]
  42.     print(key, "-", scoobies[key])
  43.  
  44. for key, value in scoobies.items():
  45.     print(key, "--", value)
  46.  
  47. for i, item in enumerate(myList):
  48.     print(i, item)
  49.  
  50. for i in range(0, 5): # simply to repeat a number of times
  51.     print(i)
  52.  
  53. for i in range(len(myList)):
  54.     print(i, "---", myList[i])
  55.  
  56. # Complete the function to return the number of upper case letters in the given string
  57. def countUpper(mystring):
  58.     # pass
  59.     # string method isupper()
  60.     count = 0
  61.     for char in mystring:
  62.         if char.isupper():
  63.             count += 1
  64.     return count
  65.  
  66. print(countUpper('Welcome to WGU')) # 4
  67. print(countUpper('Hello Mary')) # 2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement