COSC 1306 - SET 2: Loops
How many times will the loop body execute? Assume user would enter 'n', then 'n', then 'y' #Get character from user here while user_char != 'n': #Do something #get character from user here
0 The expression user_char != 'n' is False ( because user_char IS equal to 'n') So the loop body is never entered
What sequence is generated by range(7)?
0 1 2 3 4 5 6
for (index, value) in enumerate(my_list): print(index, value) if my_list = ['Greek', 'Nordic', 'Mayan'], what is the output of the program?
0 Greek 1 Nordic 2 Mayan
Given the following while loop, what is the value assigned to variable z for the given values of variables a, b and c? mult = 0 while a < 10: mult = b * a if mult > c: break a = a + 1 z = a 1) a = 1, b = 1, c = 0
1
What is the output of the following code? (Use "IL" for infinite loops) x = 0 while x > 0: print(x, end=' ') x = x - 1 print('Bye')
Bye The loop never executes because x == 0
break
a statement in a loop that causes the loop to exit immediately
Iterate over the given list using a variable called my_pet. for ______ in ['Scooter', 'Kobe', 'Bella']: #Loop body statements
my_pet
Write an expression using the random.randint() that returns a number between 0 and 5.
random.randint(0, 5)
Write the simplest range() function that generates the appropriate sequence of integers. Every integer from 10 to 20
range(10, 21)
Write the simplest range() function that generates the appropriate sequence of integers. Every 2nd integer from 10 to 20
range(10, 21, 2)
reversed()
reverse the order of the elements
Iterate while c equals 'g' while ___________: #Loop body statements go here
while c == 'g'
Given the following code, how many times will the print statement execute? for i in range(5): for j in range(10, 12): print('{}{}'.format(i, j))
10
Use input values of num_a = 15 and num_b = 10 in the above GCD program. Try to answer the questions by mentally executing the statements. If stuck, consider adding additional print statements to the program. 1) What is the value of num_a before the first loop iteration?
15 The loop hasn't executed yet, so num_a is just the input value.
Once a program is complete, one would expect to see several FIXME comments.
False
Given: for i in range(5): if i < 10: continue print(i) The loop will iterate only once.
False The loop will iterate 5 times. Continue jumps to the next iteration, thus preventing each iteration from printing anything, but continue doesn't break out of the loop.
Given: for i in range(5): if i < 10: continue print(i) The loop will print at least some output.
False i is less than 10 and will move forward and skip the print statement
Indicate whether a while loop or for loop should be used in the following scenarios: Iterate 1500 times
For (loop) The number of iterations is known, so use 'for i in range(1500)'
1. Use a for loop when the number of iterations is computable before entering the loop, as when counting down from X to 0, printing a string N times, etc. 2. Use a for loop when accessing the elements of a container, as when adding 1 to every element in a list, or printing the key of every entry in a dict, etc. 3. Use a while loop when the number of iterations is not computable before entering the loop, as when iterating until a user enters a particular character.
General Rules:
What is the output of the following code? (Use "IL" for infinite loops) x = 5 y = 18 while y >= x: print(y, end=' ') y = y - x
18 13 8
How many times will the loop body execute? Assume user would enter 'a', then 'b', then 'n' #Get character from user here while user_char != 'n': #Do something #get character from user here
2
Use input values of num_a = 15 and num_b = 10 in the above GCD program. Try to answer the questions by mentally executing the statements. If stuck, consider adding additional print statements to the program. 4) How many loop iterations will the algorithm execute?
2 The loop does not enter a third iteration because num_a == num_b (5 == 5), so execution proceeds below the while loop. Thus, 5 is output as the GCD.
How many times will the loop execute? x = 3 while x >= 1: #do something x = x - 1
3
Complete the program such that variable count ends having the number of negative values in an input list of values (the list ends with 0). So if the input is -1 -5 9 3 0, then count should end with 2. count = 0 val = Get next input While val is not 0 if __(A)__ __(B)__ val = Get next input What should statement (B) be?
count = count + 1 Variable count should be incremented each tim ea negative input value is seen. The final loop is: count = 0 val = Get next input While val is not 0 if val < 0 count = count + 1 val = Get next input
Loop iterates 10 times. i = 1 while __________: #Loop body statement goes here i = i + 1
i <= 10
infinite loop
loop that will always execute because the loop's expression is always True.
Complete the program such that variable max ends having the maximum value in an input list of positive values (the list ends with 0). So if the input is 22 5 99 3 0, then max should end as 99. max = -1 val = Get next input while val is not 0 If val > max __(B)__ val = Get next input What should expression (B) be?
max = val
Write a statement using *= that doubles the value of a variable my_var.
my_var *= 2
Write a statement using += that is equivalent to my_var = my_var + my_var / 2
my_var += my_var /2
Compute the average number of kids. #Each list item is the number of kids in a family. num_kids = [1, 1, 2, 2, 1, 4, 3, 1] total = 0 for num in num_kids: total += _______ average = total / len(num_kids)
num Each iteration of the loop adds an item of the list to a running total.
Iterate the string '911' using a variable called number. for __________________: #Loop body statements
number in '911'
Iterate over the list my_prices using a variable called price. for ________________: #Loop body statements
price in my_prices
Write the simplest range() function that generates the appropriate sequence of integers. Every integer from 0 to 500
range(501)
Iterate until c equals 'z' while ___________: #Loop body statements go here
while c != 'z' Note the word 'until', meaning to loop while c does not equal 'z'
x = 0 y = 5 z = ? while x < y: if x == z: print('x == z') break x += 1 else: print('x == y') What is the output of the code if z is 10?
x == z
What is the output of the following code? (Use "IL" for infinite loops) x = 10 while x != 3: print(x, end=' ') x = x / 2
IL (Infinite loop ) : No matter how many times 10 is divided by 2, the result will never equal to 3
Incremental programming may help reduce the number of errors in a program.
True
nested loop
a loop that appears as part of the body of another loop commonly referred to as the 'outer loop' and 'inner loop'
loop variable
a variable used to count the number of iterations
What is the output of the following code? (Use "IL" for infinite loops) x = 1 y = 3 z = 5 while not (y < x < z) print(x, end=' ') x = x + 1
1 2 3 The expression not (y < x < z) is True until x has a value of 4. Each iteration, x is printed out with a space and then incriminated by 1
For inputs 5 10 7 20 8 0, with what values should max be assigned?
-1, 5, 10, 20
What is the output of the following code? i1 = 1 while i1 < 19: i2 = 3 while i2 <= 9: print('{}{}'.format(i1,i2), end=' ') i2 = i2 + 3 i1 = i1 + 10
13 16 19 113 116 119
What sequence is generated by range(2, 5)?
2 3 4
Given the following while loop, what is the value assigned to variable z for the given values of variables a, b and c? mult = 0 while a < 10: mult = b * a if mult > c: break a = a + 1 z = a 1) a = 4, b = 5, c = 20
5
Use input values of num_a = 15 and num_b = 10 in the above GCD program. Try to answer the questions by mentally executing the statements. If stuck, consider adding additional print statements to the program. 2) What is num_a after the first and before the second iteration?
5 num_a = num_a - num_b executes; num_a = 15 - 10 = 5
Use input values of num_a = 15 and num_b = 10 in the above GCD program. Try to answer the questions by mentally executing the statements. If stuck, consider adding additional print statements to the program. 3) What is num_b after the second and before the third iteration?
5 num_a = num_a - num_b executes, giving num_a = 5. Then num_b = num_b - num_a executes, giving num_b = 5.
Given the following code, how many times will the inner loop body execute? for i in range(2): for j in range(3): # Inner loop body
6 The outer loop will iterate 2 times for i = 0, 1 while the inner loop will iterate 3 times for j = 0, 1, 2 Therefore 2 * 3 = 6
sentinel value
A value that when evaluated by the loop expression causes the loop to terminate.
A for loop combined with range() is generally preferred over while loops, since for loops are less likely to become stuck in an infinite loop situation.
True
FIXME comments provide a way for a programmer to remember what needs to be added
True
Indicate whether a while loop or for loop should be used in the following scenarios: Iterate as long as the user-entered string c is not q
While (loop) The number of iterations is not known before the loop, so use 'while c != 'q':'
Indicate whether a while loop or for loop should be used in the following scenarios: Iterate until the values of x and y are equal, where x and y are changed in the loop body.
While (loop) The number of iterations is not known before the loop, so use 'while x != y':'
Complete the program such that variable max ends having the maximum value in an input list of positive values (the list ends with 0). So if the input is 22 5 99 3 0, then max should end as 99. max = -1 val = Get next input while val is not 0 If __(A)__ __(B)__ val = Get next input What should expression (A) be?
val > max
Iterate while x is less than 100 while _________: #Loop body statements go here
while x < 100
Iterate while x is greater than or equal to 0 while ___________: #Loop body statements go here
while x >= 0
x = 0 y = 5 z = ? while x < y: if x == z: print('x == z') break x += 1 else: print('x == y') What is the output of the code if z is 3?
x == z
while loop
a programming construct that repeatedly executes an indented block of code (loop body) as long as the loop's expression is True.
Loop
a programming construct that repeatedly executes the loop's statements (loop body) while the loop's expression is true; when false, execution proceeds past the loop
What is the output of the following code? c1 = 'a' while c1 < 'b': c2 = 'a' while c2 <= 'c': print('{}{}'.format(c1, c2), end=' ') c2 = chr(ord(c2) + 1) c1 = chr(ord(c1) + 1)
aa ab ac
iteration
each execution of the loop body
range()
generates a sequence of numbers, starting at zero and ending before a value given inside the parenthesis
Loop iterates over multiples of 5 from 0 to 100 (inclusive) i = 0 while _________: #Loop body statement goes here i = i + 5
i <= 100
Loop iterates 2 times i = 1 while _________: #Loop body statement goes here i = i + 1
i <= 2
Loop iterates 99 times. i = 1 while ____________: #Loop body statement goes here i = i + 1
i <= 99
Loop iterates from -100 to 65. i = ____ while i <= 65 #Loop body statement goes here i = i + 1
i = -100
Loop iterates over the odd integers from 1 to 9 (inclusive). i = 1 while i <= 9: #Loop body statement goes here i = ____________
i = i + 2
Loop iterates over the odd integers from 211 down to 31 (inclusive). i = 211 while i >= 31 #Loop body statement goes here i = __________
i = i - 2 or i -= 2
Assign num_neg to the number of below-freezing Celsius temperatures in the list. temperatures = [30, 20, 2, -5, -15, -8, -1, 0, 5, 35] num_neg = 0 for temp in temperatures: if temp < 0: _______________________________
num_neg += 1 Each iteration of the loop adds one to num_neg if temp is less than 0.
Write the simplest range() function that generates the appropriate sequence of integers. Every integer from 5 down to -5
range(5, -6, -1)
Print scores in order from highest to lowest. Note: List is pre-sorted from lowest to highest. scores = [75, 77, 80, 85, 90, 95, 99] for scr in ____________: print(scr, end=' ')
reversed(scores)
incremental programming
starting with a simple version of the program, and then growing the program little-by-little into a complete version.
continue
statement in a loop that causes an immediate jump to the while or for loop header statement
for loop
statement that loops over each element in a container one at a time, assigning the next element to a variable that can then be used in the loop body. for (variable) in (container):
Complete the program such that variable count ends having the number of negative values in an input list of values (the list ends with 0). So if the input is -1 -5 9 3 0, then count should end with 2. count = 0 val = Get next input While val is not 0 if __(A)__ __(B)__ val = Get next input What should expression (A) be?
val < 0