Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # WEBINAR: for loops
- # FOR LOOPS are used for repeating actions for every element
- # in a container like a list, string, tuple, etc...
- myList = ["Gilligan", "Scooby", "Agent Scully"] # tv characters
- myTuple = ("Gilligan", "Castaway002", "red", "crew") # things about Gilligan
- for item in myList:
- print(item)
- for item in myTuple:
- print(item)
- mySet = {"Gilligan", "Maynard", "Kelp"} # Bob Denver roles
- for item in mySet:
- print(item)
- myString = "Just sit right back and we'll talk about Gilligan and company."
- # for char in myString: # commenting out so we don't print so much...
- # print(char)
- # how about looping over dictionaries?
- scoobies = {
- "Scooby": "a blue collar",
- "Shaggy": "green",
- "Velma": "orange",
- "Daphne": "purple",
- "Fred": "an ascot"
- }
- for key in scoobies:
- # someDict[key] --> value of that key
- # print(key, scoobies[key])
- print("{} wears {}.".format(key, scoobies[key]))
- # another way to loop over dictionaries
- for key, value in scoobies.items(): # 2 loop vars with dictionary items method
- print("{} always wears {}.".format(key, value))
- for item in range(5): # range() makes an iterable sequence from an integer
- print(item)
- # what if I'm interesting in the index position?
- for i in range(len(myList)):
- print("{} is at position {}".format(myList[i], i))
- for i, item in enumerate(myList): # enumerate() also gets you 2 loop vars: index and value at that index
- print(i,item)
- # CA 6.10.1
- # "Simon Says" is a memory game where "Simon" outputs a sequence of 10 characters
- # (R, G, B, Y) and the user must repeat the sequence. Create a for loop that compares
- # the two strings. For each match, add one point to user_score.
- # Upon a mismatch, end the game. Ex: The following patterns yield a user_score of 4:
- simon_pattern = 'RRGBRYYBGY'
- user_pattern = 'RRGBBRYBGY'
- user_score = 0
- for i in range(len(simon_pattern)):
- if simon_pattern[i] == user_pattern[i]:
- user_score += 1
- else:
- break
- print("User score:", user_score)
- # HTML is plain text... strings!
- myContainer = ("peanut butter", "bread", "milk", "cheese puffs")
- # we want this output:
- # <ul>
- # <li>peanut butter</li>
- # <li>bread</li>
- # <li>milk</li>
- # <li>cheese puffs</li>
- # </ul>
- myHTMLString = "<ul>\n"
- for item in myContainer:
- myHTMLString += "<li>{}</li>\n".format(item)
- myHTMLString += "</ul>"
- print(myHTMLString)
- # use \ for escaping (excluding) characters, or special escaped char values like \n, \t, etc
Advertisement
Add Comment
Please, Sign In to add comment