Place the files in a lab3 folder. Before leaving lab, zip up the lab3 folder, and hand the zip file in.
The following segments of code all do the same thing, but they can be done in different ways.
No loop | For Loop | While Loop |
---|---|---|
print("hello") print("hello") print("hello") print("hello") print("hello") |
for i in range(0,5): print("hello")OR for var in range(0,5): print("hello") |
i = 0 while(i < 5): print("hello") i = i + 1 |
Sample Output: >>> print_n_lte_even(5) 0 2 4 >>> print_n_lte_even(6) 0 2 4 6
mylist = list() mylist = [] mylist = ["15110", "is", "so","much", "fun"] mylist[2] mylist[4] mylist[5] # Error! mylist[0] = "Computer Science"
Loop using List Index | Loop using List Element |
---|---|
mylist = ["a", "b", "c", "d", "e", "f"] word = "" for list_index in range(0, len(mylist)): word = word + mylist[list_index] |
mylist = ["a", "b", "c", "d", "e", "f"] word = "" for list_element in mylist: word = word + list_element |
In the file loop_with_list.py:
listA = ["1","5","1","1","0"] listB = ["x", "y", "z"] Sample Output: >>>build_list_string(listA) '15110' >>>build_list_string(listB) 'xyz'
for number in range(1,4): for letter in ['a','b','c']: print(number, letter)
Please place solutions to the following two problems in nested_loops.py: Suppose we are making ice cream sundaes. We have four flavors of ice cream: vanilla, chocolate, strawberry, and pistacchio. And we have three sauces: caramel, butterscotch, and chocolate. How many different ice cream sundaes can we make? In the file nested_loops.py define a function sundaes() to systematically print out every possible combination, one per line. For example, the first line should say "vanilla ice cream sundae with caramel sauce". You should create a list to hold each class of ingredient, and use nested for loops to iterate over these lists to generate the combinations. At the end, your function should return an integer giving the total number of combinations.
To get you started here a few things you will need:
flavors = ["vanilla", "chocolate", "strawberry", "pistacchio"] sauces = ["caramel", "butterscotch", "chocolate"] print(flavor + " ice cream sundae with " + sauce + " sauce")
(optional - give it a try if you have time) Consider the following output as shown:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
Complete the missing parts so that it creates the output above. Note that the columns of numbers do not need to line up perfectly. Run your program in using python3 to test your work. HINT: Row i has i columns.
def triangle(): value = 1 row = 1 while row <= _____: column = 1 while column <= _______: if column != _______: print(value, ' ', sep = '', end = '') else: print(value) value = value + 1 column = column + 1 row = row + 1
(Optional) if you have time consider the following: