Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # for loops
- # We use loops to repeat actions
- # a WHILE loop is basically an IF statement
- # that repeats as long as its condition is true
- # a FOR loop is more for repeating something a known
- # number of times, or doing something ONCE PER ITEM
- # in some iterable container: list, string, etc
- # basic syntax of a FOR loop with a list
- myList = ["Gilligan", "Scooby", "Agent Scully"] # tv characters
- for item in myList:
- print(item)
- # or a tuple
- myTuple = ("Gilligan", "Castaway002", "red", "crew") # things about Gilligan
- for item in myTuple:
- print(item)
- # or a string, I'm only changing the loop variable name
- myString = "Just sit right back and we'll talk about Gilligan and company."
- # for char in myString:
- # print(char)
- # Note that looping over sets is exactly the same as those
- # ... even though sets have no order and thus no indexes,
- # you can still loop over them!
- scoobies = {
- "Scooby": "a blue collar",
- "Shaggy": "green",
- "Velma": "orange",
- "Daphne": "purple",
- "Fred": "an ascot"
- }
- # 2 ways to iterate over a dictionary
- for key in scoobies:
- # dictionaryName[key]
- # myList[0]
- print(key, "-", scoobies[key])
- for key, value in scoobies.items():
- print(key, "--", value)
- for i, item in enumerate(myList):
- print(i, item)
- for i in range(0, 5): # simply to repeat a number of times
- print(i)
- for i in range(len(myList)):
- print(i, "---", myList[i])
- # Complete the function to return the number of upper case letters in the given string
- def countUpper(mystring):
- # pass
- # string method isupper()
- count = 0
- for char in mystring:
- if char.isupper():
- count += 1
- return count
- print(countUpper('Welcome to WGU')) # 4
- print(countUpper('Hello Mary')) # 2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement