Download presentation
Presentation is loading. Please wait.
Published byNorah Greene Modified over 9 years ago
1
CS106 Mid-term Quiz Not counted in your grade.
2
Q1 Write code to create a variable message that refers to a string Hello world. Answer: message = “Hello world”
3
Q2 Write code to create a variable aList that refers to an empty list. Answer: aList = [] or aList = list()
4
Q3 Write code to create a variable aList that refers to a list that contains the integers 1, 2, …, 100. Answer: aList = range(1, 101)
5
Q4 Write code using a for loop that does item- based iteration of a list acids, print out each item on a separate line. Answer: for acid in acids: print acid
6
Q5 Write the same code, using index-based iteration. Answer: for idx in range(len(acids)): print acids[idx]
7
Q6 Write code that iterates over a list of strings acids that prints only the items that have length 7. Answer: for acid in acids: if len(acid) == 7: print acid
8
Q7 Write code that, given these lists: guys = [ ‘Abe’, ‘Bob’ … ] girls = [‘Ann’, ‘Bea’ … ] (each having the same length), prints out corresponding pairs, like this: Abe and Ann Bob and Bea …
9
A7 for idx in range(len(guys)): print guys[idx] + “ and “ + girls[idx]
10
Q8 Write code that creates a list of sorted integers from 1 to 1000 that contains only those integers that are not a multiple of 3 nor a multiple of 7.
11
A8 res = [] for i in range(1, 1001): if i % 3 == 0: continue if i % 7 == 0: continue res.append(i) # you could also create a list with all numbers and then remove some, but that will be slow and problematic. # Next slide has alternative solution.
12
A8 res = [] for i in range(1, 1001): if i % 3 != 0 and i % 7 != 0: res.append(i)
13
Q9 Write code to create a variable color that refers to a tuple containing integers 255, 66, 255. Answer: color = (255, 66, 255)
14
Q10 Write code that when given a list of strings cheeses, prints out each cheese on a line, preceded by its number in the list and a dot. E.g., 1.Cheddar 2.Gouda 3.Venezuelan Beaver Cheese
15
A10 for idx in range(len(cheeses)): print str(idx + 1) + “, “ + cheeses[idx]
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.