Practice Quiz: While Loops
1. In Python, what do while loops do?
- while loops tell the computer to repeatedly execute a set of instructions while a condition is true.
- while loops instruct the computer to execute a piece of code a set number of times.
- while loops branch execution based on whether or not a condition is true.
- while loops initialize variables in Python.
2. Which techniques can prevent an infinite while loop? Select all that apply.
- Change the value of a variable used in the while condition
- Use the stop keyword
- Use the break keyword
- Use the continue keyword
3. The following code contains an infinite loop, meaning the Python interpreter does not know when to exit the loop once the task is complete. To solve the problem, you will need to:
Find the error in the code
Fix the while loop so there is an exit condition
Hint: Try running your function with the number 0 as the input and observe the result.
Note that Coursera’s code blocks will time out after 5 seconds of running an infinite loop. If you get this timeout error message, it means the infinite loop has not been fixed.
def is_power_of_two(number): # This while loop checks if the "number" can be divided by two # without leaving a remainder. How can you change the while loop to # avoid a Python ZeroDivisionError? while number % 2 == 0: number = number / 2 # If after dividing by 2 "number" equals 1, then "number" is a power # of 2. if number == 1: return True return False
# Calls to the functionprint(is_power_of_two(0)) # Should be Falseprint(is_power_of_two(1)) # Should be Trueprint(is_power_of_two(8)) # Should be Trueprint(is_power_of_two(9)) # Should be False
def is_power_of_two(number):
# This while loop checks if the "number" can be divided by two
# without leaving a remainder. How can you change the while loop to
# avoid a Python ZeroDivisionError?
while number % 2 == 0:
number = number / 2
# If after dividing by 2 "number" equals 1, then "number" is a power
# of 2.
if number == 1:
return True
return False
# Calls to the function
print(is_power_of_two(0)) # Should be False
print(is_power_of_two(1)) # Should be True
print(is_power_of_two(8)) # Should be True
- def is_power_of_two(number):if number == 0:returnFalse# Exit condition for zero inputwhile number % 2 == 0:number = number / 2if number == 1:returnTruereturnFalse# Calls to the functionprint(is_power_of_two(0)) # Should be Falseprint(is_power_of_two(1)) # Should be Trueprint(is_power_of_two(8)) # Should be Trueprint(is_power_of_two(9)) # Should be False
4. Fill in the blanks to complete the while loop so that it returns the sum of all the divisors of a number, without including the number itself. As a reminder, a divisor is a number that divides into another without a remainder. To do this, you will need to:
1. Initialize the "divisor" and "total" variables with starting values
2. Complete the while loop condition
3. Increment the "divisor" variable inside the while loop
4. Complete the return statement
# Fill in the blanks so that the while loop continues to run while the# "divisor" variable is less than the "number" parameter.
def sum_divisors(number):# Initialize the appropriate variables ___ = ___ ___ = ___
# Avoid dividing by 0 and negative numbers # in the while loop by exiting the function # if "number" is less than one if number < 1: return 0
# Complete the while loop while ___: if number % divisor == 0: total += divisor # Increment the correct variable ___ += 1
# Return the correct variable return ___
print(sum_divisors(0)) # Should print 0print(sum_divisors(3)) # Should print 1# 1print(sum_divisors(36)) # Should print 1+2+3+4+6+9+12+18# 55print(sum_divisors(102)) # Should print 1+2+3+6+17+34+51# 114
# Fill in the blanks so that the while loop continues to run while the
# "divisor" variable is less than the "number" parameter.
def sum_divisors(number):
# Initialize the appropriate variables
___ = ___
___ = ___
# Avoid dividing by 0 and negative numbers
# in the while loop by exiting the function
# if "number" is less than one
if number < 1:
return 0
# Complete the while loop
while ___:
if number % divisor == 0:
total += divisor
# Increment the correct variable
___ += 1
# Return the correct variable
return ___
print(sum_divisors(0)) # Should print 0
print(sum_divisors(3)) # Should print 1
# 1
print(sum_divisors(36)) # Should print 1+2+3+4+6+9+12+18
# 55
print(sum_divisors(102)) # Should print 1+2+3+6+17+34+51
- # Fill in the blanks so that the while loop continues to run while the# “divisor” variable is less than the “number” parameter.def sum_divisors(number):# Initialize the appropriate variablesdivisor = 1total = 0# Avoid dividing by 0 and negative numbers# in the while loop by exiting the function# if “number” is less than oneif number < 1:return0# Complete the while loopwhile divisor < number:if number % divisor == 0:total += divisor# Increment the correct variabledivisor += 1# Return the correct variablereturn totalprint(sum_divisors(0)) # Should print 0print(sum_divisors(3)) # Should print 1# 1print(sum_divisors(36)) # Should print 1+2+3+4+6+9+12+18# 55print(sum_divisors(102)) # Should print 1+2+3+6+17+34+51# 114
5. Fill in the blanks to complete the function, which should output a multiplication table. The function accepts a variable “number” through its parameters. This “number” variable should be multiplied by the numbers 1 through 5, and printed in a format similar to “1x6=6” (“number” x “multiplier” = “result”). The code should also limit the “result” to not exceed 25. To satisfy these conditions, you will need to:
1. Initialize the “multiplier" variable with the starting value
2. Complete the while loop condition
3. Add an exit point for the loop
4. Increment the “multiplier" variable inside the while loop
def multiplication_table(number): # Initialize the appropriate variable ___ = ___
# Complete the while loop condition. while ___: result = number * multiplier if result > 25 : # Enter the action to take if the result is greater than 25 ___ print(str(number) + "x" + str(multiplier) + "=" + str(result)) # Increment the appropriate variable ___ += 1
multiplication_table(3) # Should print: # 3x1=3 # 3x2=6 # 3x3=9 # 3x4=12 # 3x5=15
multiplication_table(5) # Should print: # 5x1=5# 5x2=10# 5x3=15# 5x4=20# 5x5=25
multiplication_table(8) # Should print:# 8x1=8# 8x2=16# 8x3=24
def multiplication_table(number):
# Initialize the appropriate variable
___ = ___
# Complete the while loop condition.
while ___:
result = number * multiplier
if result > 25 :
# Enter the action to take if the result is greater than 25
___
print(str(number) + "x" + str(multiplier) + "=" + str(result))
# Increment the appropriate variable
___ += 1
multiplication_table(3)
# Should print:
# 3x1=3
# 3x2=6
# 3x3=9
# 3x4=12
# 3x5=15
multiplication_table(5)
# Should print:
# 5x1=5
# 5x2=10
# 5x3=15
# 5x4=20
multiplication_table(8)
# Should print:
# 8x1=8
# 8x2=16
- def multiplication_table(number):# Initialize the appropriate variablemultiplier = 1# Complete the while loop condition.while multiplier <= 5:result = number * multiplierif result > 25 :# Enter the action to take if the result is greater than 25breakprint(str(number) + “x” + str(multiplier) + “=” + str(result))# Increment the appropriate variablemultiplier += 1multiplication_table(3)# Should print:# 3×1=3# 3×2=6# 3×3=9# 3×4=12# 3×5=15multiplication_table(5)# Should print:# 5×1=5# 5×2=10# 5×3=15# 5×4=20# 5×5=25multiplication_table(8)# Should print:# 8×1=8# 8×2=16# 8×3=24
6. How are while loops and for loops different in Python?
- While loops can be used with all data types, for loops can only be used with numbers.
- For loops can be nested, but while loops can’t.
- While loops iterate while a condition is true, for loops iterate through a sequence of elements.
- While loops can be interrupted using break, for loops using continue.
7. Which option would fix this for loop to print the numbers 12, 18, 24, 30, 36?
for n in range(6,18,3): print(n*2)
for n in range(6,18,3):
- for n in range(6,18,3):print(n+2)
- for n in range(6,18+1,3):print(n*2)
- for n in range(12,36,6):print(n*2)
- for n in range(0,36+1,6):print(n)
8. Which for loops will print all even numbers from 0 to 18? Select all that apply.
- for n in range(19):if n % 2 == 0:print(n)
- for n in range(18+1):print(n**2)
- for n in range(0,18+1,2):print(n*2)
- for n in range(10):print(n+n)
9. Fill in the blanks so that the for loop will print the first 10 cube numbers (x**3) in a range that starts with x=1 and ends with x=10.
for __ in range(__,__): print(__)
for __ in range(__,__):
- for x in range(1,11):print(x**3)
10. Write a for loop with a three parameter range() function that prints the multiples of 7 between 0 and 100. Print one multiple per line and avoid printing any numbers that aren't multiples of 7. Remember that 0 is also a multiple of 7.
for ___: print(___)
for ___:
11. What is recursion used for?
- Recursion is used to create loops in languages where other loops are not available.
- We use recursion only to implement mathematical formulas in code.
- Recursion is used to iterate through files in a single directory.
- Recursion is used to call a function from inside the same function.
12. Which of these activities are good use cases for recursive programs? Check all that apply.
- Going through a file system collecting information related to directories and files.
- Creating a user account for a new employee.
- Installing or upgrading software on a computer.
- Managing permissions assigned to groups inside a company, when each group can contain both subgroups and users.
- Checking if a computer is connected to the local network.
13. Fill in the blanks to make the is_power_of function return whether the number is a power of the given base. Note: base is assumed to be a positive number. Tip: for functions that return a boolean value, you can return the result of a comparison.
def is_power_of(number, base): # Base case: when number is smaller than base. if number < base: # If number is equal to 1, it's a power (base**0). return __
# Recursive case: keep dividing number by base. return is_power_of(__, ___)
print(is_power_of(8,2)) # Should be Trueprint(is_power_of(64,4)) # Should be Trueprint(is_power_of(70,10)) # Should be False
def is_power_of(number, base):
# Base case: when number is smaller than base.
if number < base:
# If number is equal to 1, it's a power (base**0).
return __
# Recursive case: keep dividing number by base.
return is_power_of(__, ___)
print(is_power_of(8,2)) # Should be True
print(is_power_of(64,4)) # Should be True
def is_power_of(number, base):
# Base case: when number is smaller than base.
if number < base:
# If number is equal to 1, it’s a power (base**0).
return number == 1
# Recursive case: keep dividing number by base.
return is_power_of(number//base, base)
print(is_power_of(8,2)) # Should be True
print(is_power_of(64,4)) # Should be True
print(is_power_of(70,10)) # Should be False
14. The count_users function recursively counts the amount of users that belong to a group in the company system, by going through each of the members of a group and if one of them is a group, recursively calling the function and counting the members. But it has a bug! Can you spot the problem and fix it?
def count_users(group): count = 0 for member in get_members(group): count += 1 if is_group(member): count += count_users(member) return count
print(count_users("sales")) # Should be 3print(count_users("engineering")) # Should be 8print(count_users("everyone")) # Should be 18
def count_users(group):
count = 0
for member in get_members(group):
count += 1
if is_group(member):
count += count_users(member)
return count
print(count_users("sales")) # Should be 3
print(count_users("engineering")) # Should be 8
def count_users(group):
count = 0
for member in get_members(group):
ifnot is_group(member):
count += 1
else:
count += count_users(member)
return count
print(count_users(“sales”)) # Should be 3
print(count_users(“engineering”)) # Should be 8
print(count_users(“everyone”)) # Should be 18
15. Implement the sum_positive_numbers function, as a recursive function that returns the sum of all positive numbers between the number n received and 1. For example, when n is 3 it should return 1+2+3=6, and when n is 5 it should return 1+2+3+4+5=15.
def sum_positive_numbers(n): return 0
print(sum_positive_numbers(3)) # Should be 6print(sum_positive_numbers(5)) # Should be 15
def sum_positive_numbers(n):
return 0
print(sum_positive_numbers(3)) # Should be 6
- def sum_positive_numbers(n):if n == 1:return1elif n <= 0:return0else:return n + sum_positive_numbers(n-1)print(sum_positive_numbers(3)) # Should be 6print(sum_positive_numbers(5)) # Should be 15
crash course on python week 3 quiz answers
Week 3 Graded Assessment
16. Fill in the blanks to print the numbers 1 through 7.
17. Find and correct the error in the for loop. The loop should print every number from 5 to 0 in descending order.
18. Fill in the blanks to complete the “factorial” function. This function will accept an integer variable “n” through the function parameters and produce the factorials of this number (by multiplying this value by every number less than the original number [n*(n-1)], excluding 0). To do this, the function should:
accept an integer variable “n” through the function parameters;
initialize a variable “result” to the value of the “n” variable;
iterate over the values of “n” using a while loop until “n” is equal to 0;
starting at n-1, multiply the result by the current “n” value;
decrement “n” by -1.
For example, factorial 3 would return the value of 3*2*1, which would be 6.
19. Fill in the blanks to complete the “multiplication_table” function. This function should print a multiplication table, where each number is the result of multiplying the first number of its row by the number at the top of its column. Complete the range sequences in the nested loops so that “multiplication_table(1, 3)” will print:
1 2 3
2 4 6
3 6 9
20. Fill in the blanks to complete the “countdown” function. This function should begin at the “start” variable, which is an integer that is passed to the function, and count down to 0. Complete the code so that a function call like “countdown(2)” will return the numbers “2,1,0”.
21. Fill in the blanks to complete the “odd_numbers” function. This function should return a space-separated string of all odd positive numbers, up to and including the “maximum” variable that's passed into the function. Complete the for loop so that a function call like “odd_numbers(6)” will return the numbers “1 3 5”.
def odd_numbers(maximum): return_string = "" # Initializes variable as a string
# Complete the for loop with a range that includes all # odd numbers up to and including the "maximum" value. for ___:
# Complete the body of the loop by appending the odd number # followed by a space to the "return_string" variable. ___
# This .strip command will remove the final " " space # at the end of the "return_string". return return_string.strip()
print(odd_numbers(6)) # Should be 1 3 5print(odd_numbers(10)) # Should be 1 3 5 7 9print(odd_numbers(1)) # Should be 1print(odd_numbers(3)) # Should be 1 3print(odd_numbers(0)) # No numbers displayed
def odd_numbers(maximum):
return_string = "" # Initializes variable as a string
# Complete the for loop with a range that includes all
# odd numbers up to and including the "maximum" value.
for ___:
# Complete the body of the loop by appending the odd number
# followed by a space to the "return_string" variable.
___
# This .strip command will remove the final " " space
# at the end of the "return_string".
return return_string.strip()
print(odd_numbers(6)) # Should be 1 3 5
print(odd_numbers(10)) # Should be 1 3 5 7 9
print(odd_numbers(1)) # Should be 1
print(odd_numbers(3)) # Should be 1 3
print(odd_numbers(0)) # No numbers displayed
- def odd_numbers(maximum):return_string = “” # Initializes variable as a string# Complete the for loop with a range that includes all# odd numbers up to and including the “maximum” value.for i inrange(1, maximum+1, 2):# Complete the body of the loop by appending the odd number# followed by a space to the “return_string” variable.return_string += str(i) + ” “# This .strip command will remove the final ” ” space# at the end of the “return_string”.return return_string.strip()print(odd_numbers(6)) # Should be 1 3 5print(odd_numbers(10)) # Should be 1 3 5 7 9print(odd_numbers(1)) # Should be 1print(odd_numbers(3)) # Should be 1 3print(odd_numbers(0)) # No numbers displayed
22. The following code raises an error when executed. What's the reason for the error?
def decade_counter(): while year < 50: year += 10 return year
def decade_counter():
while year < 50:
year += 10
- Wrong comparison operator
- Failure to initialize the variable
- Incrementing by 10 instead of 1
- Nothing is happening inside the while loop
23. What is the first number that will be printed in the first iteration of this loop? Your answer should be only one number.
for count in range(1, 6): print(count+1)
for count in range(1, 6):
2
24. What is the final value of "y" at the end of the following nested loop code? Your answer should be only one number.
for x in range(10): for y in range(x): print(y)
for x in range(10):
for y in range(x):
8
25. The following code causes an infinite loop. Can you figure out what’s incorrect and how to fix it?
def count_to_ten(): # Loop through the numbers from first to last x = 1 while x <= 10: print(x) x = 1
count_to_ten()# Should print:# 1# 2# 3 # 4# 5# 6# 7# 8 # 9# 10
def count_to_ten():
# Loop through the numbers from first to last
x = 1
while x <= 10:
print(x)
x = 1
count_to_ten()
# Should print:
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
- Needs to have parameters passed to the function
- The “x” variable is initialized using the wrong value
- Should use a for loop instead of a while loop
- Variable “x” is assigned the value 1 in every loop
26. Fill in the blanks to print the numbers from 15 to 5, counting down by fives.
27. Fill in the blanks to complete the function “digits(n)” to count how many digits the given number has. For example: 25 has 2 digits and 144 has 3 digits.
Tip: you can count the digits of a number by dividing it by 10 once per digit until there are no digits left.
28. Fill in the blanks to complete the “even_numbers” function. This function should return a space-separated string of all positive even numbers, excluding 0, up to and including the “maximum” variable that's passed into the function. Complete the for loop so that a function call like “even_numbers(6)” will return the numbers “2 4 6”.
29. What happens when the Python interpreter executes a loop where a variable used inside the loop is not initialized?
- Nothing will happen
- Will produce a NameError stating the variable is not defined
- The variable will be auto-assigned a default value of 0
- Will produce a TypeError
30. What is the final value of “x” at the end of this for loop? Your answer should be only one number.
for x in range(1, 10, 3): print(x)
for x in range(1, 10, 3):
- 7
31. Fill in the blanks to print the even numbers from 2 to 12.
32. Find and correct the error in the for loop below. The loop should check each number from 1 to 5 and identify if the number is odd or even.
33. The following code is supposed to add together all numbers from x to 10. The code is returning an incorrect answer, what is the reason for this?
x = 1
sum = 5
while x <= 10:
sum += x
x += 1
print(sum)
# Should print 55
- Should use a for loop instead of a while loop
- The code is not inside of a function
- Not incrementing the iterator (x)
- The “sum” variable is initialized with the wrong value
34. The following code causes an infinite loop. Can you figure out what is incorrect?
def test_code(num): x = num while x % 2 == 0: x = x / 2
test_code(0)
def test_code(num):
x = num
while x % 2 == 0:
x = x / 2
- When called with 0, it triggers an infinite loop
- The modulo operator is used incorrectly
- Missing an else statement
- Missing the continue keyword
35. Find and correct the error in the for loop below. The loop should print every even number from 2 to 12.
36. Fill in the blanks to complete the “all_numbers” function. This function should return a space-separated string of all numbers, from the starting “minimum” variable up to and including the “maximum” variable that's passed into the function. Complete the for loop so that a function call like “all_numbers(3,6)” will return the numbers “3 4 5 6”.
37. Fill in the blanks to complete the function “even_numbers(n)”. This function should count how many even numbers exist in a sequence from 0 to the given “n”number, where 0 counts as an even number. For example, even_numbers(25) should return 13, and even_numbers(6) should return 4.
38. Fill in the blanks to complete the “divisible” function. This function should count the number of values from 0 to the “max” parameter that are evenly divisible (no remainder) by the “divisor” parameter. Complete the code so that a function call like “divisible(100,10)” will return the number “10”.
39. Fill in the blanks to complete the “rows_asterisks” function. This function should print rows of asterisks (*), where the number of rows is equal to the “rows” variable. The number of asterisks per row should correspond to the row number (row 1 should have 1 asterisk, row 2 should have 2 asterisks, etc.). Complete the code so that “row_asterisks(5)” will print:
*
* *
* * *
* * * *
* * * * *
40. What is the initial value of the “outer_loop” variable on the first iteration of the nested "inner_loop"? Your answer should be only one number.
for outer_loop in range(2, 6+1):
for inner_loop in range(outer_loop):
if inner_loop % 2 == 0:
print(inner_loop)
2
41. What number is printed at the end of this code?
num1 = 0
num2 = 0
for x in range(5):
num1 = x
for y in range(14):
num2 = y + 3
print(num1 + num2)
20
42. The following code causes an infinite loop. Can you figure out what’s missing and how to fix it?
def count_numbers(first, last):
# Loop through the numbers from first to last
x = first
while x <= last:
print(x)
count_numbers(2, 6)
# Should print:
# 2
# 3
# 4
# 5
# 6
- Missing the break keyword
- Wrong comparison operator is used
- Missing an if-else block
- Variable x is not incremented