INTRODUCTION – Loops
In this module, you’ll explore the fascinating world of loops in Python, gaining practical insights into how they enable efficient and dynamic code execution. You’ll begin with while loops, understanding their versatility in continuously executing code while a condition holds true. Along the way, you’ll learn to identify and resolve infinite loop errors, ensuring your loops run as intended and without disruption.
The journey continues with for loops, a powerful tool for iterating over data sets. You’ll uncover the practical applications of the range() function, enhancing your ability to control loop execution effectively. The module also delves into handling common errors associated with for loops, equipping you with the skills to troubleshoot and resolve these issues confidently.
To deepen your understanding, you’ll explore the combination of nested loops and if statements, enabling you to create more complex and dynamic scripts. By the end of this module, you’ll have mastered both while and for loops, gaining indispensable tools for creating efficient Python programs.
Learning Objectives
- Implement while loops to execute code continuously while a condition remains true.
- Identify and correct infinite loops when working with while loops.
- Utilize for loops to iterate over a block of code effectively.
- Apply the range() function to control the behavior of for loops.
- Employ nested while and for loops alongside if statements for more complex logic.
- Identify and troubleshoot common errors encountered while using loops.
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. (CORRECT)
- 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.
Correct. while loops will keep executing the same group of instructions until a specified loop condition stops being true.
2. Which techniques can prevent an infinite while loop? Select all that apply.
- Change the value of a variable used in the while condition (CORRECT)
- Use the stop keyword
- Use the break keyword (CORRECT)
- Use the continue keyword
Accurate! When using a numeric variable to control the iterations of a while loop it essential to modify the variable within the loop extremely that it eventually satisfies the condition to exit the loop.
Differently the circuit leave keep to do indefinitely extremely the go importantword get work old to end amp spell circuit untimely. It commonly Applyed within a nested if-else conditional statement inside the loop providing a way to exit when a specific condition is met.
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:
if number == 0:
return False
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
print(is_power_of_two(9)) # Should be False
Awesome! You fixed a tricky error that was hard to find and the function now behaves correctly.
4. Write a function that takes an argument n and returns the sum of integers from 1 to n. For example, if n=5, your function should add up 1+2+3+4+5 and return 15. If n is less than 1, just return 0. Use a while loop to calculate this sum.
def sum_of_integers(n):
if n < 1:
return 0
i = 1
sum = 0
while i<=n:
sum = sum + i
i = i + 1
return sum
print(sum_of_integers(3)) # should print 6
print(sum_of_integers(4)) # should print 10
print(sum_of_integers(5)) # should print 15
Great work! You’ve written a while loop and gotten Python to do the work for you.
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 “1×6=6” (“number” x “multiplier” = “result”). The code should also limit the “result” to not exceed 25. To satisfy these conditions, you will need to:
Initialize the “multiplier” variable with the starting value
Complete the while loop condition
Add an exit point for the loop
Increment the “multiplier” variable inside the while loop
def multiplication_table(number):
# Initialize the appropriate variable
multiplier = 1
# Complete the while loop condition.
while multiplier<=5:
result = number * multiplier
if result > 25:
# Enter the action to take if the result > 25
break
print(str(number) + "x" + str(multiplier) + "=" + str(result))
# Increment the appropriate variable
multiplier += 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
Correct. You completed the multiplication table with all of the required criteria, and it looks great!
PRACTICE QUIZ: FOR LOOPS
1. How are while loops and for loops different in Python?
- while loops can be used with all data types; for loops can be used only 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. (CORRECT)
- while loops can be interrupted using break; you interrupt for loops using continue.
while
loops: Keep running as long as the specified condition remains true. They’re great for scenarios where the number of iterations isn’t predetermined, such as waiting for a user to input valid data.
2. 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):
print(n+2) - for n in range(6,18+1,3):
print(n*2) (CORRECT) - for n in range(12,36,6):
print(n*2) - for n in range(0,36+1,6):
print(n)
Great job! To include 18 in the range, add 1 to it. The second parameter could be written as 18+1 or 19.
3. 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) (CORRECT) - 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) (CORRECT)
This loop will print all even numbers from 0 to 18. The range of “n” starts at 0 and ends at 18 (the endpoint value of 19 is excluded), with “n” incrementing by the default of 1 in each iteration. The if statement checks if “n” is divisible by 2 using the modulo operator (%). If the condition is true, it will print the value of “n” and continue to the next iteration.
This loop will print all even numbers from 0 to 18. The range of “n” starts at 0 and ends at 9 (the endpoint value of 10 is excluded), with “n” incrementing by the default of 1 in each iteration. The expression (n+n), where n is an integer, is equivalent to (n*2). This ensures the result is always an even number, with the final iteration printing the result of 9+9.
4. 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 x in range(1,11):
print(x**3)
Awesome! You’re getting Python to do all the work for you.
6. Which of these options would output just the vowels from the following string? Select all that apply.
input = "Four score and seven years ago"
- The slice() method can be used to slice a string.
- If the starting index is negative, Python generates a runtime error.
- If the starting index is negative, Python counts backward from the end of the string. (CORRECT)
- When slicing a string, you must always provide both the starting and ending indexes.
Correct! Negative indexes in Python allow you to extract slices from the end of a string. For example, string[-1]
refers to the last character, string[-2]
to the second-to-last character, and so on. You can also use negative indexes in slicing, like string[-3:]
, which extracts the last three characters of the string. This is a convenient way to work with the end of a string without needing to know its length.
7. Which of these statements is true about slicing strings?
- Stop intrusive activity
- Monitor system and network activity (CORRECT)
- Collect and analyze system information for abnormal activity (CORRECT)
- Alert on possible intrusions (CORRECT)
IDS is an application that keeps track of system and network activities and generates alerts for suspected intrusions. It also retrieves and analyzes system data to detect any abnormal or unusual behavior.
PRACTICE QUIZ: RECURSION
1. 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. (CORRECT)
You nailed it! You can call a function within itself to traverse a hierarchy of objects, such as directories and subdirectories.
2. 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. (CORRECT)
- 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. (CORRECT)
- Checking if a computer is connected to the local network.
Exactly! Since directories can have nested subdirectories, a recursive program is ideal for navigating through this hierarchy, allowing it to process each directory and its contents without needing to manually handle each level.
You got it! As the groups can contain both groups and users, this is the kind of problem that is a great use case for a recursive solution.
3. 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 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
Nice job! You’ve made the code check for powers of numbers by reducing the problem to a smaller one.
4. Recursion is a process where a function calls itself one or more times with modified values to accomplish a task. This technique can be particularly effective when solving complex problems that can be broken down into smaller, simpler problems of the same type. In the provided code, the count_users function uses recursion to count the number of users that belong to a group within a company’s system. It does this by iterating through each member of a group, and if a member is another group, it recursively calls count_users to count the users within that subgroup. However, there is a bug in the code! 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 -= 1
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
Well done, you! You spotted the problem that was causing groups to be counted when we only wanted to count users!
5. In the while loops practice quiz, you were asked to write a function to calculate the sum of all positive numbers between 1 and n. Rewrite the function using recursion instead of a while loop. Remember that when n is less than 1, the function should return 0 as the answer.
def sum_positive_numbers(n):
if n < 1:
return 0
return (n)+(sum_positive_numbers(n-1))
print(sum_positive_numbers(3)) # Should be 6
print(sum_positive_numbers(5)) # Should be 15
Here is your output:
6
15
Great work! You’ve really nailed writing recursive functions!
6. Which of the following scenarios would benefit the most from using a recursive function to solve the problem?
- You need to print out a list of the employees in your company.
- You need to know how many files are present in a single directory of your computer.
- You need to create a family tree, showing several generations of your ancestors, with all of their children. (CORRECT)
- You need to calculate the square root of numbers 1 through 10.
Great job! You’re getting the concept of recursion and when it’s a better solution than the traditional looping techniques.
MODULE 3 GRADED ASSESSMENT
1. Fill in the blanks to print the even numbers from 2 to 12.
- Answer:
number = 2 # Initialize the variable
while number<=12: # Complete the while loop condition
print(number, end=" ")
number = number+2 # Increment the variable
# Should print 2 4 6 8 10 12
2. Find and correct the error in the for loop. The loop should print every number from 5 to 0 in descending order.
- Answer:
for number in range(5,-1,-1):
print(number)
# Should print:
# 5
# 4
# 3
# 2
# 1
# 0
3. 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.
- Answer:
def digits(n):
count = 0
if n == 0:
count += 1
while n>0: # Complete the while loop condition
# Complete the body of the while loop. This should include
# performing a calculation and incrementing a variable in the
# appropriate order.
n//=10
count+=1
return count
print(digits(25)) # Should print 2
print(digits(144)) # Should print 3
print(digits(1000)) # Should print 4
print(digits(0)) # Should print 1
4. Fill in the blanks to complete the “sequence” function. This function should print a sequence of numbers in descending order, from the given “high” variable to the given “low” variable. The range should make the loop run two times. Complete the range sequences in the nested loops so that the “sequence(1, 3)” function call prints the following:
3, 2, 1
3, 2, 1
- Answer:
- Answer:
def sequence(low, high):
# Complete the outer loop range to make the loop run twice
# to create two rows
for x in range(2):
# Complete the inner loop range to print the given variable
# numbers starting from "high" to "low"
# Hint: To decrement a range parameter, use negative numbers
for y in range(high,low-1,-1):
if y == low:
# Don’t print a comma after the last item
print(str(y))
else:
# Print a comma and a space between numbers
print(str(y), end=", ")
sequence(1, 3)
# Should print the sequence 3, 2, 1 two times, as shown above.
5. 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”.
- Answer:
def divisible(max, divisor):
count = 0 # Initialize an incremental variable
for x in range(max): # Complete the for loop
if x % divisor == 0:
count += 1 # Increment the appropriate variable
return count
print(divisible(100, 10)) # Should be 10
print(divisible(10, 3)) # Should be 4
print(divisible(144, 17)) # Should be 9
6. 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”.
- Answer:
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 in range(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 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
7. What happens when the Python interpreter executes a loop where a variable used inside the loop is not initialized?
- The variable will be auto-assigned a default value of 0
- Will produce a NameError stating the variable is not defined
- Will produce a TypeError (CORRECT)
- Nothing will happen
Correct
8. 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)
- Missing an else statement
- The modulo operator is used incorrectly
- When called with 0, it triggers an infinite loop (CORRECT)
- Missing the continue keyword
Correct
9. Fill in the blanks to print the numbers 1 through 7.
- Answer:
number = 1 # Initialize the variable
while number<8: # Complete the while loop condition
print(number, end=" ")
number += 1 # Increment the variable
# Should print 1 2 3 4 5 6 7
Correct
10. 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.
- Answer:
for number in range(1,6):
if number % 2 == 0:
print("even")
else:
print("odd")
# Should print:
# odd
# even
# odd
# even
# odd
Correct
11. 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:
*
* *
* * *
* * * *
* * * * *
- Answer:
def rows_asterisks(rows):
# Complete the outer loop range to control the number of rows
for x in range(1,rows+1):
# Complete the inner loop range to control the number of
# asterisks per row
for y in range(x):
# Prints one asterisk and one space
print("*", end=" ")
# An empty print() function inserts a line break at the
# end of the row
print()
rows_asterisks(5)
# Should print the asterisk rows shown above
Correct
12. Fill in the blanks to complete the “counter” function. This function should count down from the “start” to “stop” variables when “start” is bigger than “stop”. Otherwise, it should count up from “start” to “stop”. Complete the code so that a function call like “counter(3, 1)” will return “Counting down: 3, 2, 1” and “counter(2, 5)” will return “Counting up: 2, 3, 4, 5”.
- Answer:
def counter(start, stop):
if start > stop:
return_string = "Counting down: "
while start >= stop: # Complete the while loop
return_string += str(start) # Add the numbers to the "return_string"
if start > stop:
return_string += ","
start -= 1 # Increment the appropriate variable
else:
return_string = "Counting up: "
while start<=stop: # Complete the while loop
return_string += str(start) # Add the numbers to the "return_string"
if start < stop:
return_string += ","
start += 1 # Increment the appropriate variable
return return_string
print(counter(1, 10)) # Should be "Counting up: 1,2,3,4,5,6,7,8,9,10"
print(counter(2, 1)) # Should be "Counting down: 2,1"
print(counter(5, 5)) # Should be "Counting up: 5"
Correct
13. 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”.
- Answer:
def all_numbers(minimum, maximum):
return_string = "" # Initializes variable as a string
# Complete the for loop with a range that includes all
# numbers up to and including the "maximum" value.
for number in range(minimum,maximum+1):
return_string += str(number)
return_string += ' '
# This .strip command will remove the final " " space
# at the end of the "return_string".
return return_string.strip()
print(all_numbers(2,6)) # Should be 2 3 4 5 6
print(all_numbers(3,10)) # Should be 3 4 5 6 7 8 9 10
print(all_numbers(-1,1)) # Should be -1 0 1
print(all_numbers(0,5)) # Should be 0 1 2 3 4 5
print(all_numbers(0,0)) # Should be 0
Correct
14. 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”.
- Answer:
def all_numbers(minimum, maximum):
return_string = "" # Initializes variable as a string
# Complete the for loop with a range that includes all
# numbers up to and including the "maximum" value.
for number in range(minimum,maximum+1):
return_string += str(number)
return_string += ' '
# This .strip command will remove the final " " space
# at the end of the "return_string".
return return_string.strip()
print(all_numbers(2,6)) # Should be 2 3 4 5 6
print(all_numbers(3,10)) # Should be 3 4 5 6 7 8 9 10
print(all_numbers(-1,1)) # Should be -1 0 1
print(all_numbers(0,5)) # Should be 0 1 2 3 4 5
print(all_numbers(0,0)) # Should be 0
Correct
15. What happens when the Python interpreter executes a loop where a variable used inside the loop is not initialized?
- Will produce a TypeError
- Nothing will happen
- The variable will be auto-assigned a default value of 0Will produce a NameError stating the variable is not defined (CORRECT)
Correct
16. The following code causes an infinite loop. Can you figure out what’s incorrect and how to fix it?
- Answer:
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
- The “x” variable is initialized using the wrong value
- Needs to have parameters passed to the function
- Should use a for loop instead of a while loop
- Variable “x” is assigned the value 1 in every loop (CORRECT)
Correct
17. Find and correct the error in the for loop below. The loop should print every even number from 2 to 12.
- Answer:
for number in range(2,12+1,2):
print(number)
# Should print:
# 2
# 4
# 6
# 8
# 10
# 12
Correct
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.
- Answer:
def factorial(n):
result = n
start = n
n -= 1
while n>0: # The while loop should execute as long as n is greater than 0
result *= n # Multiply the current result by the current value of n
n -= 1 # Decrement the appropriate variable by -1
return result
print(factorial(3)) # Should print 6
print(factorial(9)) # Should print 362880
print(factorial(1)) # Should print 1
Correct
19. 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”
- Answer:
def countdown(start):
x = start
if x > 0:
return_string = "Counting down to 0: "
while x>=0: # Complete the while loop
return_string += str(x) # Add the numbers to the "return_string"
if x > 0:
return_string += ","
x -= 1 # Decrement the appropriate variable
else:
return_string = "Cannot count down to 0"
return return_string
print(countdown(10)) # Should be "Counting down to 0: 10,9,8,7,6,5,4,3,2,1,0"
print(countdown(2)) # Should be "Counting down to 0: 2,1,0"
print(countdown(0)) # Should be "Cannot count down to 0"
Correct
20. 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
- The “sum” variable is initialized with the wrong value (CORRECT)
- The code is not inside of a function
- Not incrementing the iterator (x)
- Should use a for loop instead of a while loop
Correct
21. 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.
- Answer:
def even_numbers(n):
count = 0
current_number = 0
while current_number<=n: # Complete the while loop condition
if current_number % 2 == 0:
count += 1 # Increment the appropriate variable
current_number += 1 # Increment the appropriate variable
return count
print(even_numbers(25)) # Should print 13
print(even_numbers(144)) # Should print 73
print(even_numbers(1000)) # Should print 501
print(even_numbers(0)) # Should print 1
Correct
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
- Failure to initialize the variable (CORRECT)
- Nothing is happening inside the while loop
- Wrong comparison operator
- Incrementing by 10 instead of 1
Correct
23. The following code causes an infinite loop. Can you figure out what’s missing and how to fix it?
- Answer:
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
- Variable x is not incremented (CORRECT)
- Missing an if-else block
- Missing the break keyword
- Wrong comparison operator is used
Correct
CONCLUSION – Loops
In conclusion this module has provided a comprehensive understanding of loops in Python enhancing your ability to leverage them effectively in various scenarios. you’ve gained facility inch exploitation spell loops for perpetual Effectiveness spell too acquisition however to important and work Problems care myriad loops. The practical Use of for loops notably in iterating over Informationsets and your familiarity with the range() Role have broadened your capacity to manage structured Information efficiently. also the module has equipped you with troubleshooting skills to resolve common errors in for loops strengthening your coding practices. these skills inch circuit structures leave Method arsenic amp base for creating further prompt and active python programs inch the prospective