Advertisement
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...
- # (as opposed to a WHILE loop, which is like an IF statement that repeats as long as it's true)
- # let's get some iterable objects in here
- myList = ["Gilligan", "Scooby", "Agent Scully", "Fonzie"] # tv characters
- myTuple = ("Gilligan", "Castaway002", "red", "crew") # things about Gilligan
- # Basic syntax of a for loop
- # for __ in ___:
- # Looping over a L I S T
- for item in myList: # I use "item" as my loop variable, any valid name works but keep it simple and descriptive!
- print(item) # print(item, end=" ")
- # Looping over a T U P L E.. it's the same! Same with SETS too.
- for item in myTuple:
- print(item)
- # S T R I N G S --> each loop iteration is a single character
- myString = "Just sit right back and we'll talk about Gilligan and company."
- # for char in myString: # I tend to use "char" or "ch" or "letter" when looping over a string
- # print(char, end="\n")
- # D I C T I O N A R I E S
- # dictionaries have KEYS and VALUES
- scoobiesDCT = {
- "Scooby": "a blue collar", # key: value,
- "Shaggy": "green",
- "Velma": "orange",
- "Daphne": "purple",
- "Fred": "an ascot"
- }
- for key in scoobiesDCT: # for loop var for a dictionary is the KEY
- # dict[key] --> gets you the value for that key
- print(key, "always wears", scoobiesDCT[key])
- # an alternate way to for loop over a dictionary
- # for __, __ in dict.items()
- for k, v in scoobiesDCT.items():
- print(k, "almost always wears", v)
- # R A N G E
- # range() function creates an iterable sequence from a number (integer)
- for n in range(5):
- print(n)
- # sometimes the INDEX is as important as the value at that index
- for i in range(len(myList)):
- print(i, myList[i])
- # or with ENUMERATE we get 2 variables
- for i, item in enumerate(myList):
- # print(str(i), "-->", item)
- print("{} --> {}".format(i, item))
- # some ZyBooks loop problems...
- # CA 6.5.2
- contact_emails = {
- 'Sue Reyn' : 's.reyn@email.com',
- 'Mike Filt': 'mike.filt@bmail.com',
- 'Nate Arty': 'narty042@nmail.com'
- }
- # output for each: s.reyn@email.com is Sue Reyn, etc
- for contact in contact_emails:
- print(contact_emails[contact], "is", contact)
- # or...
- for key in contact_emails: # the book used "contact" as the var, I'll stick my fav "item"
- print("{} is {}".format(contact_emails[key], key))
- # CA 6.10.1
- user_score = 0
- simon_pattern = 'RRGBRYYBGY'
- user_pattern = 'RRGBBRYBGY'
- # for i in range(10):
- for i in range(len(simon_pattern)):
- if simon_pattern[i] == user_pattern[i]:
- user_score += 1
- else:
- break # end loop when they no longer match
- print("User score: ", user_score) # 4
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement