Skip to content

In this module you’ll explore the intricacies of loops in Python! You’ll learn how to use while loops to continuously execute code, as well as how to identify infinite loop errors and how to fix them. You’ll also learn to use for loops to iterate over data, and how to use the range() function with for loops. You’ll also explore common errors when using for loops and how to fix them.

Learning Objectives

  • Use the range() function to control for loops
  • Utilize for loops to iterate over a block of code
  • Identify and fix infinite loops when using while loops
  • Implement while loops to continuously execute code while a condition is true
  • Use nested while and for loops with if statements
  • Identify and correct common errors when using loops

While Loops


Video: Introduction to Loops

In the next few videos, you will learn how to automate repetitive tasks using three techniques: while loops, for loops, and recursion. Each of these techniques tells the computer to repeat a task, but each takes a slightly different approach. You will learn how to write the code for each and how to know when to use one technique instead of the others.

Benefits of automating repetitive tasks:

  • Computers are great at repeating tasks accurately and without getting tired.
  • Automation can save you a lot of time and free you up for more interesting tasks.
  • Automation can be used to perform complex tasks that would be difficult or impossible to do manually.

Examples of automated tasks:

  • Copying files to a bunch of computers on a network
  • Sending personalized emails to a list of users
  • Verifying that a process is still running
  • Managing software rollouts

Conclusion:

Automating repetitive tasks is a powerful tool that can save you time and help you to be more efficient. By learning the three techniques discussed in this video, you will be able to automate a wide variety of tasks.

Introduction

Loops are a way to execute a block of code repeatedly. This can be useful for performing a task a certain number of times, or until a certain condition is met.

In Python, there are two main types of loops: while loops and for loops.

While loops

While loops execute a block of code as long as a certain condition is met. The syntax for a while loop is as follows:

while condition:
    # block of code to be executed

The condition is a Boolean expression that evaluates to True or False. If the condition is True, the block of code is executed. If the condition is False, the loop terminates.

For example, the following code prints the numbers from 0 to 9:

i = 0
while i < 10:
    print(i)
    i += 1

In this example, the condition is i < 10. This means that the loop will continue to execute as long as the value of i is less than 10. When i reaches 10, the condition becomes False and the loop terminates.

For loops

For loops execute a block of code a specific number of times. The syntax for a for loop is as follows:

for variable in sequence:
    # block of code to be executed

The sequence is a collection of values, such as a list or a range. The variable is used to iterate over the sequence.

For example, the following code prints the numbers from 0 to 9:

for i in range(10):
    print(i)

In this example, the sequence is the range from 0 to 9. The variable i is used to iterate over the range.

Conclusion

Loops are a powerful tool that can be used to automate repetitive tasks. They are an essential part of any Python programmer’s toolkit.

Here are some additional tips for using loops in Python:

  • Use while loops for tasks that need to be repeated until a certain condition is met.
  • Use for loops for tasks that need to be repeated a specific number of times.
  • Use break statements to terminate a loop early.
  • Use continue statements to skip the current iteration of a loop.

By following these tips, you can use loops to write efficient and effective Python code.

[MUSIC] Hi there, and welcome back. Before we dive back in I
want to first say well done. We’ve learned a lot of new skills
in a short amount of time and tackled some pretty tricky concepts. None of this stuff is easy and
you’re doing so great. So we’ve got some fun concepts
lined up for the next few videos. So far we’ve seen how to
organize our code and functions. We’ve also made our code
branch in two different paths depending on certain conditions. In this module we’ll learn how to get
computers to do repetitive tasks, which is another
cornerstone of programming. As we’ve called out before, computers
are great at repeating the same task over and over. They never get bored or make a mistake. You could ask a computer to do the same
calculation a thousand times and the first result would be just as
accurate as the last, which isn’t something we
can say about us humans. Have you ever tried to do something
a thousand times in a row? It’d be enough to drive you loopy,
which is why in this course, we’re going to learn how to leave
the loops up to the computer. The ability to accurately
perform repetitive tasks and never get tired is why computers are so
great for automation. The automated task could be anything like
copying files to a bunch of computers on a network, sending personalized
emails to a list of users, or verifying that a process is still running. It doesn’t matter how complex the task is,
your computer will do it as many times as you tell it to, which leaves you time for
more interesting things like planning future hardware
needs, or managing software roll outs. In the next few videos we’ll
explore three techniques for automating repetitive tasks. These are while loops,
for loops, and recursion. Each of these techniques are used to
tell the computer to repeat a task, but each takes a slightly different approach. We’re going to learn how
to write the code for each and how to know when to use one
technique instead of the others. So, are you ready? Let’s get started.

Video: What is a while loop?

A while loop instructs your computer to continuously execute your code based on the value of a condition. This works in a similar way to branching if statements, but the body of the loop can be executed multiple times instead of just once.

Example:

x = 0
while x < 5:
  print("Not there yet.")
  x += 1
print(x)

This code will print the message “Not there yet.” five times, followed by the value of x, which is 5.

Benefits of using while loops:

  • While loops can be used to automate repetitive tasks.
  • While loops can be used to keep asking for input until the user provides a valid response.
  • While loops can be used to try an operation until it succeeds.

Conclusion:

While loops are a powerful tool that can help you to write more efficient code. By learning how to use while loops, you can automate repetitive tasks and create more complex programs.

A while loop is a programming construct that repeats a block of code until a specific condition is met. The syntax for a while loop is as follows:

while condition:
    # block of code to be executed

The condition is a Boolean expression that evaluates to True or False. If the condition is True, the block of code is executed. If the condition is False, the loop terminates.

For example, the following code prints the numbers from 0 to 9:

i = 0
while i < 10:
    print(i)
    i += 1

In this example, the condition is i < 10. This means that the loop will continue to execute as long as the value of i is less than 10. When i reaches 10, the condition becomes False and the loop terminates.

While loops can be used to perform a variety of tasks, such as:

  • Printing a list of numbers
  • Asking the user for input until a valid value is entered
  • Calculating a sum or average
  • Sorting a list of items

It is important to use while loops carefully to avoid infinite loops. An infinite loop is a loop that never terminates because the condition is never met. To avoid infinite loops, it is important to make sure that the condition eventually becomes False.

Here are some tips for using while loops:

  • Use a while loop when you need to repeat a block of code until a specific condition is met.
  • Make sure that the condition eventually becomes False to avoid infinite loops.
  • Use break statements to terminate a loop early if necessary.
  • Use continue statements to skip the current iteration of a loop.

By following these tips, you can use while loops to write efficient and effective code.

[MUSIC] First off,
we’re going to talk about while loops. While loops instruct your computer to
continuously execute your code based on the value of a condition. This works in a similar way
to branching if statements. The difference here is that the body of
the block can be executed multiple times instead of just once. Check out this program. Can you guess what it does? Before we execute it to find out,
let’s go through it together line by line. In the first line we’re assigning
the value of 0 to the variable x. We call this action initializing,
to give an initial value to a variable. In the line after that,
we’re starting the while loop. We’re setting a condition for this loop
that x needs to be smaller than 5. Right now we know that x is 0 since
we’ve just initialized it, so this condition is currently true. On the next two lines, we have
a block that’s indented to the right. Here, we can use what we
learned about functions and conditionals to identify that
this is the while loop’s body. There are two lines in
the body of the loop. In the first line, we print a message
followed by the current value of x. In the second line,
we increment the value of x. We do this by adding 1 to its current
value and assigning it back to x. So after the first execution of the body
of the loop, x will be 1 instead of 0. Because this is a loop,
the computer doesn’t just continue executing with
the next line in the script. Instead, it loops back around
to re-evaluate the condition for the while loop. And because 1 here is still smaller than
5, it executes the body of the loop again. It then prints the message and
once more increments x by 1. So the x is now 2. The computer will keep doing this until
the condition isn’t true anymore. In this example, the condition will be
false when x is no longer smaller than 5. Once the condition is false, the loop
finishes, and the next line is executed. And finally, the last line of our
code prints the last value of x. So now that this code
makes a bit more sense, what do you think will
happen when we execute it? Ready to find out? Let’s execute the code and
see what happens. So we had five lines with the message,
Not there yet, and then at the end of the script
the value of x was 5. This was a simple example of
how a while loop behaves. As we’ve said before, we’re learning
the building blocks of programming. Once you know those building blocks, you can combine them to create
more complex expressions. As an IT specialist,
while loops can be super helpful. You can use them to keep asking for a
username if the one provided isn’t valid, or maybe try an operation
until it succeeds. Knowing how to construct these
expressions can help you get your computer to do a whole lot
with only a little bit of code. It’s pretty powerful stuff
we’re learning here. Now that you’ve got an idea
of how a while loop works, let’s spice it up with another example.

x = 0
while x < 5:
  print("Not there yet, x=" + str(x))
  x = x + 1
print("x=" + str(x))How many times will "

Not there yet” be printed?

5

You got it! The variable x starts at 0 and gets incremented once per iteration, so there are 5 iterations for which x is smaller than 5.

Video: More while Loop Examples

This video builds on the previous video by discussing how to use while loops inside functions and how to use more complex conditions in while loops.

Example:

def my_function(n):
    x = 1
    while x <= n:
        print("Attempt number:", x)
        x += 1

my_function(5)

Output:

Attempt number: 1
Attempt number: 2
Attempt number: 3
Attempt number: 4
Attempt number: 5

This example shows how to use a while loop inside a function. The function takes a parameter, n, and prints the message “Attempt number:” followed by the value of x until x is greater than n.

Using more complex conditions in while loops:

The condition used in a while loop can be more complex than simply comparing two numbers. For example, you can call a separate function that evaluates the condition, or you can use logical operators to combine the values of several expressions.

Example:

def get_username():
    username = input("Enter your username: ")
    return username

def valid_username(username):
    if len(username) >= 6:
        return True
    else:
        return False

def my_function():
    username = get_username()
    while not valid_username(username):
        print("Invalid username. Please try again.")
        username = get_username()

my_function()

This example shows how to use a more complex condition in a while loop. The my_function() function asks the user for a username and then validates it using the valid_username() function. If the username is invalid, the function keeps asking the user for a new username until they enter a valid one.

Conclusion:

While loops are a powerful tool that can help you to write more efficient code. By learning how to use while loops, you can automate repetitive tasks and create more complex programs.

Here are some more examples of while loops in Python:

  • Printing the numbers from 1 to 10:
i = 1
while i <= 10:
  print(i)
  i += 1
  • Counting the number of even numbers between 1 and 100:
even_count = 0
i = 2
while i <= 100:
  if i % 2 == 0:
    even_count += 1
  i += 1

print("There are", even_count, "even numbers between 1 and 100.")
  • Finding the factorial of a number:
def factorial(n):
  factorial = 1
  i = 1
  while i <= n:
    factorial *= i
    i += 1
  return factorial

print("The factorial of 5 is", factorial(5))
  • Generating a Fibonacci sequence:
def fibonacci(n):
  a, b = 0, 1
  i = 0
  while i < n:
    print(a, end=" ")
    a, b = b, a + b
    i += 1

fibonacci(10)

These are just a few examples of the many ways that while loops can be used in Python. By understanding the basics of while loops, you can use them to solve a variety of problems.

Here are some additional tips for writing while loops:

  • Use a clear and concise condition. The condition should be easy to understand and should be evaluated to true or false.
  • Use a variable to control the loop. The variable should be incremented or decremented inside the loop so that the condition eventually becomes false and the loop terminates.
  • Avoid infinite loops. Make sure that the condition in the while loop will eventually become false.
  • Use break to exit the loop early. The break statement can be used to exit the loop even if the condition is still true.
  • Use continue to skip the current iteration of the loop. The continue statement can be used to skip the current iteration of the loop and go to the next iteration.

By following these tips, you can write while loops that are clear, concise, and efficient.

[MUSIC] In the last video, we saw a very
simple example of a while loop. We looked at the basic syntax
of the loop and how it works. Let’s now apply this knowledge
to a similar example, but this time with a while
loop inside a function. Can you work out what this function does? In this example, we start out by
initializing a variable called x. In this case,
we initialize it with a value of 1. Then, we enter our while loop which
checks to see if the value inside of the x variable is less than the parameter
n that the function received. If that comparison evaluates to true, then the code inside
the while block is executed. Say we pass a value of 5 as
a parameter to this function. In the first pass through the loop,
x is always equal to 1, so the comparison: 1 smaller than or
equal to 5 would be true and we then enter the body of the loop. In the body, we first print a message
indicating that the current attempt number and
then we increase the value of x by 1. To increment the number we’re using a
slightly different expression than before. x +=1 is a shorthand version of x = x+1. You can use either expression since
they both mean the same thing. The process continues until the result
of the comparison isn’t true anymore, which happens when x is bigger than n. In our current example,
this would be when the value of x is 6. Let’s see it in action. In these past examples, we’ve used
the simple conditions of a number being smaller, or smaller or
equal than another number. These are common conditions, but they’re by no means the only
conditions you can have in a while loop. It’s common, for example, to call a separate function
that evaluates the condition, like this. In this case, there’s a lot of
code hidden behind functions and it’s doing stuff we don’t see. There’s a get username function
that asks the user for a username and a valid_username
function that validates that username. And all this is happening in
just a handful of characters. As you can see, you can pack a lot of
punch into just a short line of code. In this case, the body of the while
loop will be executed until the user enters a valid username. The important thing to remember
is that the condition used by the while loop needs to
evaluate to true or false. It doesn’t matter if this is done
by using comparison operators or calling additional functions. The conditions used in while loops can
also become more complex if we use the logical operators that we
encountered when looking into branching, and, or, and not. This lets us combine the values of several
expressions to get the result we want. Okay, we’ve now covered what a while
loop is and learned its syntax and basic behavior. Some of this stuff can be a bit tricky and
you’re doing great, keep sticking with it. Next, we’re going to do a rundown of some
of the most common pitfalls that you may come across when writing your own loops. Head on over to the next
video to get started.

Can you work out what this function does? Try passing different parameters to the attempts function to see what it does.

def attempts(n):
    x = 1
    while x <= n:
        print("Attempt " + str(x))
        x += 1
    print("Done")
    
attempts(6)

Video: Why Initializing Variables Matters

When writing loops, avoid the following common mistakes:

  • Forgetting to initialize variables with the right value.
  • Reusing variables without setting the correct value from the start, if the variable has already been used in the program.

To avoid these mistakes, check that you are initializing all the variables you want to use before you use them.

If you are stuck or unsure about something, don’t forget to ask for help in the discussion forums.

To master programming, practice, practice, practice!

In programming, a variable is a named location in memory that stores data. When you create a variable, you need to initialize it with a value. This means assigning it a starting value, which can be anything, such as a number, a string, or a Boolean value.

Initializing variables is important for several reasons:

  • It ensures that the variable has a value. If you do not initialize a variable, it will have the default value of None, which is an undefined value. This can lead to unexpected behavior in your program.
  • It makes your code more readable and maintainable. When you initialize variables, you are explicitly stating what value they should have. This makes it easier to understand your code and to debug it if something goes wrong.
  • It can improve the performance of your code. When you initialize variables, the compiler can optimize your code by knowing the initial value of the variable. This can lead to faster execution times.

Here are some examples of why initializing variables matters:

  • Suppose you have a variable called counter that you want to use to count the number of times a loop executes. If you do not initialize counter, it will have the default value of None. This means that the first time the loop executes, the value of counter will be None. The next time the loop executes, the value of counter will still be None. This will continue until the loop terminates.
  • Suppose you have a variable called name that you want to use to store the name of a user. If you do not initialize name, it will have the default value of None. This means that the first time you try to print the value of name, you will get an error.
  • Suppose you have a variable called price that you want to use to store the price of an item. If you do not initialize price, it will have the default value of None. This means that the first time you try to add price to another variable, you will get an error.

To avoid these problems, always initialize variables with a value. This will make your code more readable, maintainable, and efficient.

Here are some tips for initializing variables:

  • Use a meaningful name for the variable. This will make your code easier to understand.
  • Use a consistent data type for the variable. This will help to prevent errors.
  • Initialize the variable with a value that is appropriate for its data type.
  • Do not forget to initialize the variable!

By following these tips, you can ensure that your variables are initialized correctly and that your code is free of errors.

[MUSIC] As we’ve called out earlier,
writing loops allows us to get our computer to do repetitive work for us. Since one of the main benefits of
writing scripts in IT is to save time by automating repetitive tasks,
loops are super useful. So let’s make sure you avoid some of
the most common mistakes people make when writing loops. One of the most common errors is
forgetting to initialize variables with the right value. We’ve all made this mistake
when starting to code. Remember how in the earlier examples
we initialized our variable x to 0 in one case and to 1 in the other. When we forget to initialize the variable
two different things can happen. The first possible outcome and the easiest to catch
is that Python might raise an error telling us that we’re using a variable we
haven’t defined, which looks like this. As we’ve done with other
errors we’ve come across, we can look at the last line
to understand what’s going on. This error type is a name error, and the message that comes after it says
we’re using an undefined variable. It’s straightforward to fix, we just need to initialize the variable
before using it, like this: Fixed. Now, there’s a second issue we might face
if we forget to initialize variables with the right value. We might have already used
the variable in our program. In this case, if we reuse the variable
without setting the correct value from the start,
it will still have the value from before. This can lead to some
pretty unexpected behavior. Check out this script.
Can you spot the problem? In the first block, we correctly
initialize x to 1 and sum to 0 and then iterate until x equals 10,
summing up all the values in between. So by the end of that block, sum equals the result of adding all
the numbers from 1 to 10 and x is 10. In the second part of the code, the
original intention was to get the product of all the numbers from 1 to 10.
But if you look closely, you can see that we’re initializing the
product but forgetting to initialize x, so x is still 10. This means that when
the while condition gets checked, x is already 10 at
the start of the iteration. The while condition is false before it
even starts and the body never executes. Let’s see how this problem would look. In this case, it might be harder to catch the problem
because python doesn’t raise an error. The problem here is that our product
variable has the wrong value. If you have a loop that’s gone rogue and
is not behaving as expected, it’s a good idea to check if all
the variables are correctly initialized. In this example, we need to set x back
to 1 before starting the second loop. As always, the best way to learn
is to practice it yourself. Make sense? Remember, if you ever feel stuck or
a little unsure about something you can always ask for
help in the discussion forums. These forums are there to let you get
the help you need when you need it, so don’t forget to use them. So, to recap, whenever you’re writing
a loop check that you’re initializing all the variables you want to
use before you use them. And don’t worry if you don’t
get it right the first time, we’ve all been there when
learning how to code. As we’ve called out before, the way
to master programming is to practice, practice, practice. Keep practicing until
you’re comfortable and even then it’s still
okay to make mistakes. So don’t feel like you can’t
loop back around to review and practice everything we’ve covered so far.

In this code, there’s an initialization problem that’s causing our function to behave incorrectly. Can you find the problem and fix it?

def count_down(start_number):
  current = start_number
  while (current > 0):
    print(current)
    current -= 1
  print("Zero!")

count_down(3)

Here is your output: 3 2 1 Zero! You nailed it! By initializing the current variable you got the function to behave correctly.

Video: Infinite Loops and How to Break Them

Infinite loops are loops that keep executing and never stop. This can happen if the condition for the loop is never met, or if the loop body does not change the condition.

To avoid infinite loops, it is important to:

  • Initialize all variables before the loop.
  • Make sure that the loop body changes the condition for the loop.
  • Add a break statement to the loop body so that you can exit the loop early if needed.

Here is an example of an infinite loop:

while True:
  print("This loop will never stop!")

To fix this loop, we can add a break statement to the loop body:

while True:
  print("This loop will never stop!")
  break

This will cause the loop to exit after the first iteration.

Infinite loops can also be useful. For example, you might want to use an infinite loop to keep running a program until the user presses Ctrl+C.

Here is an example of an infinite loop that is used to keep running a program until the user presses Ctrl+C:

import signal

def interrupt_handler(signal, frame):
  print("Exiting program.")
  sys.exit(0)

signal.signal(signal.SIGINT, interrupt_handler)

while True:
  # Do something
  pass

This program will keep running until the user presses Ctrl+C. When the user presses Ctrl+C, the interrupt_handler() function is called, which prints “Exiting program.” and exits the program.

It is important to note that infinite loops should always have a way to be broken, either by the user or by the program itself.

Infinite Loops and How to Break Them in Python

An infinite loop is a loop that never stops running. This can happen if the condition for the loop is always true, or if the loop body does not change the condition.

Infinite loops can be useful in some cases, but they can also be a problem. For example, if you accidentally write an infinite loop in your program, it can cause your program to crash or to use up all of your computer’s resources.

Here is an example of an infinite loop in Python:

while True:
  print("This loop will never stop!")

This loop will keep running forever, because the condition True is always true.

To break an infinite loop, you can use the break keyword. The break keyword will cause the loop to exit immediately.

Here is an example of how to use the break keyword to break an infinite loop:

while True:
  print("This loop will never stop!")
  break

This loop will print “This loop will never stop!” once, and then it will exit.

You can also use the break keyword to break out of a loop early if a certain condition is met.

For example, the following loop will print all of the numbers from 1 to 10, unless the user presses the q key:

while True:
  number = input("Enter a number: ")
  if number == "q":
    break
  print(number)

If the user presses the q key, the loop will exit immediately.

It is important to note that infinite loops should always have a way to be broken, either by the user or by the program itself. This is to prevent the program from crashing or from using up all of the computer’s resources.

Here are some additional tips for avoiding infinite loops in Python:

  • Initialize all variables before the loop.
  • Make sure that the loop body changes the condition for the loop.
  • Use the break keyword to exit the loop early if needed.

Infinite loops can be a useful tool, but they should be used with caution. By following the tips above, you can avoid accidentally writing infinite loops in your Python programs.

You may remember by now that while loops use a condition
to check when to exit. The body of the while
loop needs to make sure that the condition being
checked will change. If it doesn’t change,
the loop may never finish and we get what’s
called an infinite loop, a loop that keeps
executing and never stops. Check out this example. It uses the modulo operator
that we saw a while back. This cycle will finish for positive and negative
values of x. But what would happen
if x was zero? The remainder of 0
divided by 2 is 0, so the condition would be true. The result of dividing 0
by 2 would also be zero, so the value of x
wouldn’t change. This loop would go on forever, and so we’d get an infinite loop. If our code was called with
x having the value of zero, the computer would just
waste resources doing a division that would never
lead to the loop stopping. The program would be
stuck in an infinite loop circling background endlessly,
and we don’t want that. All that looping might
make your computer dizzy. To avoid this, we
need to think about what needs to happen for
a loop to be successful. In this example, we said that x needs to be different than zero. So we could nest this while loop inside an if statement
just like this. With this approach,
the while loop is executed only when x is not zero. Alternatively, we could add
the condition directly to the loop using a logical
operator like in this example. This makes sure we only enter
the body of the loop for values of x that are both
different than zero and even. Talking about infinite
loops reminds me of one of the first times I used
while loops myself. I wrote a script that emailed me as a way of verifying
that the code worked, and while some
condition was true, I forgot to exit the loop. Turns out those e-mails get sent faster than once per second. As you can imagine, I got about 500 e-mails before I
realized what was going on. Infinitely grateful for
that little lesson. When you’re done
laughing at my story, remember, when you’re
writing loops, it’s a good idea to take
a moment to consider the different values
a variable can take. This helps you make sure
your loop won’t get stuck. If you see that your program is running forever
without finishing, have a second look at
your loops to check there’s no infinite loop
hiding somewhere in the code. While you need to watch
out for infinite loops, they are not always a bad thing. Sometimes you actually want
your program to execute continuously until some
external condition is met. If you’ve used the ping utility
on Linux or macOS systems, or ping-t on a Windows system, you’ve seen an infinite
loop in action. This tool will keep sending packets and printing
the results to the terminal unless you send it the interrupt signal,
usually pressing Ctrl+C. If you were looking at
the program source code, you’ll see that it uses an
infinite loop to do this with a block of code with instructions to keep sending
the packets forever. One thing to call out
is it should always be possible to break the loop
by sending a certain signal. In the ping example, that signal is the
user pressing Ctrl+C. In other cases, it
could be that the user pressed the button on a
graphical application, or that another program
sent a specific signal, or even that a time
limit was reached. In your code, you could have an infinite loop that
looks something like this. In Python, we use the
break keyword which you can see here to signal that the current loop
should stop running. We can use it not only to stop
infinite loops but also to stop a loop early if the code has already
achieved what’s needed. So quick refresh. How do you avoid the
most common pitfalls when writing while loops? First, remember to
initialize your variables, and second, check that your
loops won’t run forever. Wow. All this talk of loops is making me
feel a little loopy. I’m going to have to go and lie down while you do the
next practice quiz. Best of luck, and meet me over in the next video
when you’re done.

The following code causes an infinite loop. Can you figure out what’s missing and how to fix it?
def print_range(start, end):
	# Loop through the numbers from start to end
	n = start
	while n <= end:
		print(n)
		n += 1

print_range(1, 5)  # Should print 1 2 3 4 5 (each number on its own line) 

Here is your output:
1
2
3
4
5

Great work! You’ve managed to fix the error in the code that
was causing an infinite loop!

Practice Quiz: Practice Quiz: While Loops

What are while loops in Python?

Fill in the blanks to make the print_prime_factors function print all the prime factors of a number. A prime factor is a number that is prime and divides another without a remainder.

The following code can lead to an infinite loop. Fix the code so that it can finish successfully for all numbers.
Note: Try running your function with the number 0 as the input, and see what you get!

Fill in the empty function so that it returns the sum of all the divisors of a number, without including it. A divisor is a number that divides into another without a remainder.

he multiplication_table function prints the results of a number passed to it multiplied by 1 through 5. An additional requirement is that the result is not to exceed 25, which is done with the break statement. Fill in the blanks to complete the function to satisfy these conditions.

For Loops


Video: What is a for loop?

For loops are used to iterate over a sequence of values. A simple example is to iterate over a sequence of numbers, like this:

for x in range(5):
  print(x)

This will print the numbers 0, 1, 2, 3, and 4.

For loops can also be used to iterate over a list of strings, like this:

names = ["Alice", "Bob", "Carol"]
for name in names:
  print("Hello, " + name + "!")

This will print the greetings “Hello, Alice!”, “Hello, Bob!”, and “Hello, Carol!”.

For loops are a powerful tool for automating tasks. For example, you could use a for loop to copy files from one directory to another, or to process the contents of a file.

Here is an example of how to use a for loop to calculate the total sum and average of a list of numbers:

numbers = [1, 2, 3, 4, 5]
sum = 0
length = 0

for number in numbers:
  sum += number
  length += 1

average = sum / length

print("The sum is " + str(sum))
print("The average is " + str(average))

This code will print the following output:

The sum is 15
The average is 3.0

For loops are a versatile tool that can be used to automate a variety of tasks. As an IT specialist, you will likely use for loops frequently in your work.

A for loop in Python is a programming construct that allows you to iterate over a sequence of values. This means that you can execute a block of code multiple times, once for each value in the sequence.

For loops are very useful for automating tasks, such as processing data in a list or file, or performing the same operation on multiple objects.

To create a for loop in Python, you use the following syntax:

for variable in sequence:
  code block

The variable will be assigned each value in the sequence, in turn. The code block will be executed for each value of the variable.

Here is a simple example of a for loop:

numbers = [1, 2, 3, 4, 5]

for number in numbers:
  print(number)

This code will print the numbers 1, 2, 3, 4, and 5 to the console.

You can also use for loops to iterate over other types of sequences, such as strings, tuples, and dictionaries. For example, the following code will print each character in a string:

string = "Hello, world!"

for character in string:
  print(character)

This code will print the following output to the console:

H
e
l
l
o
,
 
w
o
r
l
d
!

For loops can also be used to iterate over nested sequences. For example, the following code will print each item in a list of lists:

list_of_lists = [[1, 2, 3], [4, 5, 6]]

for inner_list in list_of_lists:
  for item in inner_list:
    print(item)

This code will print the following output to the console:

1
2
3
4
5
6

For loops are a powerful tool in Python, and they can be used to automate a wide variety of tasks. As you learn more about Python, you will find that for loops are one of the most commonly used programming constructs.

[MUSIC] Okay, how are you doing? If all this talk of loops is starting to
make your head spin, remember that there’s nothing wrong with looping back around and
reviewing what you’ve learned. It’s the quickest way to stop feeling
like you’re running in circles. All right, feeling good? Great. Then we’re ready for
a different type of loop. In this video,
we’re going to meet the for loop. A for
loop iterates over a sequence of values. A very simple example of a for loop is to iterate over
a sequence of numbers, like this. Notice how the structure is kind
of similar to the structures we’ve already seen. The first line indicates
the distinguishing keyword. In this case, that’s for. And it ends with a colon. The body of the loop is indented to
the right, like we saw in the while loop, the if block, and
the function definitions. What’s different in this case
is that we have the keyword in. Also, between the for keyword and in
keyword, we have the name of a variable. This variable will take each of the values
in the sequence that loop iterates through. So in this example, it’ll iterate through
a sequence of numbers generated using the range function. There are two important things I want to
call out about this range function. First, in Python and
a lot of other programming languages, a range of numbers will start
with the value 0 by default. Second, the list of numbers generated
will be one less than the given value. In the simple example here, x will take the values 0, 1, 2, 3, and 4. Let’s check this out. So there, we have a very basic for loop. It iterates over a sequence of numbers
generated by the range function. When using a for loop, we point
the variable defined between for and in, in this case, x,
at each element of the sequence. This means on the first
iteration x points at 1. On the second iteration,
it points at 2, and so on. Whatever code we put in the body
of the loop will be executed on each of the values, one value at a time. As we said earlier, the loop’s body can do a lot of
things with the values it iterates. For example, you could have a function
to calculate the square of a number, and then use a for loop to sum the squares
of the numbers in a range. Iterating over numbers looks very similar
to the while loop examples we showed before. So you may be wondering why have two loops
that look like they do the same thing? Well, the power of the for
loop is that we can use it to iterate over a sequence of values of any type,
not just a range of numbers. Think all the way back to our very
first Python example in this course. Remember our trusty “hi friends” script? In it, we saw a for
loop that iterated over a list of strings. It looks like this. We’ll talk a lot more
about lists later on. But for now, you only need to know that we
can construct lists using square brackets, and separate the elements
in them with commas. In this example,
we’re iterating a list of strings. And for each of the strings in the list,
we’re printing a greeting. The sequence that the for loop iterates
over could contain any type of element, not just strings. For example, we could iterate over a list of numbers
to calculate the total sum and average. Here’s one way of doing this. Here, we’re defining a list of values. After that, we’re initializing
two variables, sum and length, that will update in the body of the for
loop. In the for loop, we’re iterating
over each of the values in the list, adding the current value to the sum of
values, and then also adding 1 to length, which calculates how many
elements there are in the list. Once we’ve gone through the whole list,
we print out the sum and the average. We’ll keep using for loops in our examples
every time we want to iterate over the elements of any sequence and
operate with them. Some examples of sequences that we can
iterate are the files in a directory, the lines in a file,
the processes running on a machine. And there’s a bunch of others. So as an IT specialist, you’ll use for
loops to automate tons of stuff. For example, you might use them to
copy files to machines, process the contents of files, automatically
install software, and a lot more. A few weeks ago, I had to update a lot of
files with different values depending on their contents. So I used a for loop in a script
to iterate over all the files. Then, my script took different
actions based on an if condition and updated all of those files for me. It would have taken me forever if I
had done this manually file by file. If you’re wondering when you
should use for loops and when you should use while loops,
there’s a way to tell. Use for loops when there’s a sequence
of elements that you want to iterate. Use while loops when you want to repeat
an action until a condition changes. And if whatever you’re trying to do can
be done with either for or while loops, just use whichever one’s your favorite. I’m more of a “while” gal myself,
but it’s totally your call. Next up, we’ve put together more examples
to help get you more practice with for loops and discover some of the cool
things you could do with them.

Video: More for Loop Examples

The range function can generate a sequence of numbers. It can receive one, two, or three parameters.

  • If it receives one parameter, it will create a sequence one by one from zero until one less than the parameter received.
  • If it receives two parameters, it will create a sequence one by one from the first parameter until one less than the second parameter.
  • If it receives three parameters, it will create a sequence starting from the first number and moving towards the second number. But this time, the jumps between the numbers will be the size of the third number, and again, it will stop before the second number.

Here are some examples:

# range(10) will generate the sequence [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(1, 10) will generate the sequence [1, 2, 3, 4, 5, 6, 7, 8, 9]
range(0, 10, 2) will generate the sequence [0, 2, 4, 6, 8]

The range function is a useful tool for iterating over sequences of numbers in Python.

Example 1: Print the sum of all the even numbers from 1 to 10:

sum = 0
for i in range(2, 11, 2):
  sum += i

print(sum)

Output:

30

Example 2: Print the squares of all the numbers from 1 to 10:

for i in range(1, 11):
  print(i * i)

Output:

1
4
9
16
25
36
49
64
81
100

Example 3: Print the reverse of a string:

string = "Hello, world!"

reversed_string = ""
for character in string[::-1]:
  reversed_string += character

print(reversed_string)

Output:

!dlrow ,olleH

Example 4: Iterate over a list of dictionaries:

my_list = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}]

for person in my_list:
  print(person["name"])
  print(person["age"])

Output:

Alice
25
Bob
30

Example 5: Iterate over a nested list:

my_nested_list = [[1, 2, 3], [4, 5, 6]]

for inner_list in my_nested_list:
  for item in inner_list:
    print(item)

Output:

1
2
3
4
5
6

These are just a few examples of how to use for loops in Python. For loops are a powerful tool that can be used to automate a variety of tasks. As you learn more about Python, you will find that for loops are one of the most commonly used programming constructs.

In the last video, we talked about the
range function, and how it generates a sequence of numbers starting with zero. Sometimes, though, we don’t
want to start with zero. For these situations,
the range function also allows us to specify the first element of
the list to generate. We do that by passing two parameters to the
function instead of one, like in the next example. Product = 1 for n in range(1,10): product = product * n print(product). In this example,
we’re calculating the products of all
numbers from 1 to 10. For this operation,
it’s important that we start with one and not with zero. If we’d started with zero, the whole product would be zero. Additionally, we can specify a third parameter to change
the size of each step. This means that instead
of going one by one, we could have a larger
difference between the elements. Let’s check out this
example when you might want to do
something like this. First, we’re defining a
function that converts a temperature value from
Fahrenheit to Celsius, and we’re simply using a
conversion formula to do that. Then we have a for loop
that starts at zero, and goes up to 100
in steps of 10. Notice that we’re using 101 for the upper limit
instead of 100. We’re doing this
because the range never includes the last element, and we want to include
100 in our range. The body of the for-loop
prints the value in Fahrenheit and the value in Celsius creating a
conversion table. Let’s see this in action. That example got you
feeling the heat. Don’t worry, there’s a quick rundown of what we’ve learned. The range function
can receive one, two or three parameters. If it receives one parameter, it will create a
sequence one by one from zero until one less than
the parameter received. If it receives two parameters, it will create a
sequence one by one from the first parameter until one less than the
second parameter. Finally, if it receives
three parameters, it will create a
sequence starting from the first number and moving
towards the second number. But this time, the jumps
between the numbers will be the size of
the third number, and again, it will stop
before the second number. This might sound like a lot to
remember, but don’t panic. As we’ve said before,
you don’t have to try to memorize it all,
just keep practicing. It’ll soon become second nature. To help you practice, we’ve
included all of this in a handy cheat sheet to refer
to whenever you need it. You’ll find that in
the next reading.

Reading: A Closer Look at the Range() Function

Reading

Video: Nested for Loops

Nested for loops are two or more for loops inside each other. They are useful for solving problems that require iterating over multiple lists or sequences.

Example:

# Print all possible Domino Tiles
for left in range(7):
    for right in range(left, 7):
        print("[" + str(left) + "|" + str(right) + "]", end=" ")
    print()

This code will print the following output:

[0|0] [0|1] [0|2] [0|3] [0|4] [0|5] [0|6]
[1|1] [1|2] [1|3] [1|4] [1|5] [1|6]
[2|2] [2|3] [2|4] [2|5] [2|6]
[3|3] [3|4] [3|5] [3|6]
[4|4] [4|5] [4|6]
[5|5] [5|6]
[6|6]

Another example:

# Print all possible team pairings for a basketball league
teams = ['Dragons', 'Wolves', 'Pandas', 'Unicorns']

for home_team in teams:
    for away_team in teams:
        if home_team != away_team:
            print(home_team + " vs " + away_team)

This code will print the following output:

Dragons vs Wolves
Dragons vs Pandas
Dragons vs Unicorns
Wolves vs Pandas
Wolves vs Unicorns
Pandas vs Unicorns

Important considerations:

  • Nested for loops can be slow, especially if the lists or sequences they are iterating over are large.
  • It is important to use conditional statements to avoid printing unwanted results.
  • Nested for loops should only be used when necessary.

Conclusion:

Nested for loops are a powerful tool, but they should be used with caution. Be aware of their potential performance impact and use conditional statements to avoid printing unwanted results.

Nested for loops in Python

Nested for loops are two or more for loops inside each other. They can be used to solve problems that require multiple iterations, such as printing all possible team pairings in a league or iterating over a list of elements multiple times.

To create a nested for loop in Python, you simply place one for loop inside another for loop. The inner for loop will iterate over its list once for each iteration of the outer for loop.

For example, the following code will print all possible team pairings in a league:

teams = ["Dragons", "Wolves", "Pandas", "Unicorns"]

for home_team in teams:
  for away_team in teams:
    if home_team != away_team:
      print(home_team + " vs " + away_team)

This code will print the following output:

Dragons vs Wolves
Dragons vs Pandas
Dragons vs Unicorns
Wolves vs Dragons
Wolves vs Pandas
Wolves vs Unicorns
Pandas vs Dragons
Pandas vs Wolves
Pandas vs Unicorns
Unicorns vs Dragons
Unicorns vs Wolves
Unicorns vs Pandas

Nested for loops can also be used to iterate over a list of elements multiple times. For example, the following code will iterate over the list of elements twice and print each element twice:

list_of_elements = [1, 2, 3, 4, 5]

for i in range(2):
  for element in list_of_elements:
    print(element)

This code will print the following output:

1
2
3
4
5
1
2
3
4
5

Nested for loops can be a powerful tool for solving problems that require multiple iterations. However, it is important to use them carefully, as they can slow down your computer if the lists you are iterating over are large.

Here are some additional tips for using nested for loops effectively:

  • Only use nested loops when necessary. There are often other ways to solve problems that do not require nested loops.
  • Be careful of the size of the lists you are iterating over. If the lists are large, the nested loop may take a long time to complete.
  • Consider using functions to break up your code into smaller, more manageable pieces. This can make your code easier to read and debug.

Overall, nested loops are a powerful tool that can be used to solve a variety of problems. However, it is important to use them carefully and be aware of the potential performance implications.

You’re doing great getting your head around all these loops. I think you’re
ready for something a little bit more complex. We’re going to explore
what happens when you get loops inside of loops. Does that make your head spin? Don’t worry, we’re
about to break it down for you with a
couple of examples. Have you ever played
dominoes before? There’s a bunch of fun games you can play with these tiles. In case you’re not familiar, each Domino Tiles has two
numbers represented by a collection of dots carved
on each half of the tile. The numbers go from zero to six. Tiles can be rotated so that
each combination of numbers is represented only once
in a set of Domino Tiles. In other words,
the two-three tile is the same as the
three-two tile, and there’s only one per set. Now, imagine we wanted to write a program that prints each
Domino Tile in a set. If we take all of the tiles
that have zero on the left, we can print tiles with numbers from zero to six on the right. That should be easy to
do with a for loop. But what about tiles that
have one on the left? Well, we need to skip
the one zero tile, because that one was already
printed as zero one. So we can print a list
of tiles with one on the left and numbers from
one to six on the right. When we look at two, we would need to skip both
zero and one, and so on. Are you following along? How do you think we’d write
the code for this? Turning this into
code means that we’d need to write two for loops, one inside the other. This is what we call
nested for loops. Check out how this
looks on Python code. for left in range(7): for right in range(left,7): print(“[” + print(“[” + str(left) + “|” + print(“[” + str(left) + “|” + str(right) + “]”, end print(“[” + str(left) + “|” + str(right) + “]”, end=” “)
print() In this code, we’re using a new parameter that we
passed to the print function. This parameter is called end=” “. Normally, once print has taken the content we passed and
written it to the screen, then it writes a special
character that creates a new line called the
newline character. If we want print to write something else instead of
the newline character, we use the end=” ” parameter, like we see in this example. Notice how the second for loop iterates over a
different number of elements each time it’s called as the value of left changes. Depending on what you want to achieve with your nested loops, you may want both loops to always go through the same
number of elements. Or you might want the second loop to connect to the first one. Let’s look at a
different example. Let’s say you run a local girl’s basketball
league in your town. You have four teams that will play against each
other in the league, both at home and away. You’ve stored the names of the teams in a list, like this:
teams = [ ‘Dragons’, ‘Wolves’, ‘Pandas’, ‘Unicorns’] We want to write a
script that will output all possible
team pairings. For this, the order of the names matters
because for each game, the first name will
be the home team and the second name
is the away team. Of course, what we don’t want to do is have a team
playing against itself. So what statement do we
need to use to avoid that? To do this, we need to use
a conditional that makes sure we only print the pairing when the
names are different. Check out what this looks like. for home_team in teams: for away_team in teams: if home_team != away_team: print(home_team + print(home_team + “ vs ” + away_team) Success! As you can see, nested loops are super useful for solving certain problems,
like pairing teams. What it doesn’t solve
is the question: who would win in a face-off
between dragons and unicorns? If only there were
some code for that. Anyway, we’ve seen that nested
loops are a handy tool, but we need to be
careful not to just blindly apply them
to any problem. Why? Well, because the longer the list your code
needs to iterate through, the longer it takes your
computer to complete the task. Let’s say your manager asks you to do an operation that will run through a list
of 10,000 elements. If the operation takes one
millisecond per element, the whole loop would
take one millisecond times 10,000 to complete, which is 10 seconds. Now, imagine we add a nested loop that has to go over the
same 10,000 elements. This means that each iteration of the outside loop would do a full iteration of
the inside loop, which again, would take ten seconds to go
through the whole list. So now, the whole iteration
takes 10,000 times 10 seconds, which is 100,000 seconds, that’s over 27 hours. I have the patience of a gnat, so that would definitely
not work for me. This doesn’t mean we
shouldn’t use nested loops. They are a useful
tool when solving problems that require them, but we need to be careful of
where and how we use them. Throughout this course,
and one is coming up, we’ll look at a lot of
techniques that can help us pick the right tool to use
for each type of problem. Up next, we’ll look into some common errors that you might come across when writing your for loops and what
to do about them.

Video: Common Errors in for Loops

  • Trying to iterate over a single element. This can be fixed by using the range() function or by putting the element in a list.
  • Iterating over the letters of a string when you want to iterate over the whole string. This can be fixed by putting the string in a list.

Examples:

# Trying to iterate over a single element
for x in 25:
    print(x)

# This will raise a TypeError because integers are not iterable.

# Fixing the error using the range() function
for x in range(25):
    print(x)

# This will print the numbers from 0 to 24.

# Fixing the error by putting the element in a list
for x in [25]:
    print(x)

# This will also print the number 25.

# Iterating over the letters of a string when you want to iterate over the whole string
def greet_friends(friends):
    for friend in friends:
        print(f"Hello, {friend}!")

# Calling the function with a string instead of a list
greet_friends("Barry")

# This will print the following output:
#
# Hello, B!
# Hello, a!
# Hello, r!
# Hello, r!
# Hello, y!

# Fixing the error by putting the string in a list
greet_friends(["Barry"])

# This will print the following output:
#
# Hello, Barry!

Conclusion:

By being aware of these common mistakes, you can avoid them and write more efficient and robust for loops.

Common Errors in for Loops in Python

For loops are one of the most fundamental programming concepts, and they are used extensively in Python. However, there are a few common mistakes that programmers can make when using for loops. In this tutorial, we will discuss the most common errors in for loops in Python and how to avoid them.

Trying to iterate over a single element

One of the most common mistakes in for loops is trying to iterate over a single element. For example, the following code will produce a TypeError because integers are not iterable:

for x in 25:
    print(x)

Output:

TypeError: 'int' object is not iterable

To fix this error, you need to make sure that the for loop is iterating over a sequence of elements. You can use the range() function to create a sequence of numbers, or you can iterate over a list or other sequence of elements.

Using an incorrect range() function

Another common mistake in for loops is using an incorrect range() function. The range() function takes three arguments: the start value, the end value, and the step value. The start value is the first value in the sequence, the end value is the last value in the sequence, and the step value is the amount by which the sequence increments.

For example, the following code will print the numbers from 0 to 9, inclusive:

for x in range(10):
    print(x)

Output:

0
1
2
3
4
5
6
7
8
9

However, the following code will not print anything, because the end value is less than the start value:

for x in range(10, 0):
    print(x)

Output:

To fix this error, make sure that the end value is greater than or equal to the start value.

Iterating over a string when you want to iterate over the whole string

Another common mistake in for loops is iterating over a string when you want to iterate over the whole string. For example, the following code will print each letter of the string “hello”:

for x in "hello":
    print(x)

Output:

h
e
l
l
o

If you want to iterate over the whole string, you need to put the string inside a list. For example, the following code will print the string “hello”:

for x in ["hello"]:
    print(x)

Output:

hello

Conclusion

By avoiding these common mistakes, you can write more efficient and bug-free Python code.

We’ve now seen how
to write for loops, combine them with functions, nest a for loop inside
a different loop, and even combine a nested
loop with conditionals. Nice job, you’re
chugging right along. But before we’re
done with for loops, let’s check out some
common mistakes you may come across while
trying this yourself. As we’ve called out already, for loops iterate over sequences. The interpreter will refuse to iterate over a single element. As you see here: for x in 25:
print(x) In this example, we’re trying to iterate
over the number 25. Python prints a
TypeError telling us that integers
are not iterable. There are two solutions
to this problem, depending on what
we’re trying to do. If we want to go from zero to 25, then we use the range function: for x in range(25):
print(x), but if we’re trying to
iterate over a list that has 25 as the only element, then it needs to
be a list and that means writing it between
square brackets: for x in [25]: for x in [25]:
print(x) You might be wondering why
you’d ever want to iterate over a list of one element
and that’s a good question. Well, this kind of
issue usually happens when you have a function
with a for loop inside it, which is iterating
over the elements of a list received by parameter. Say for example, you have
a function that fixes the permissions of a list of
files received by parameter, and you want to call
this function to fix the permissions of just
one specific file. To do that, you need to pass the file as the single
element of a list. Let’s check this out with some
code we’re familiar with, our friendliest of Python
examples, hi, friends. We’re going to modify it to have the greetings inside a function. We’ve defined a greet
friends function, that receives a list
by parameter and iterates over that list,
greeting each friend. But what if we only want to greet one friend instead of four? Well, we still need
to define a list, but with only one element. But first, let’s see what would happen if we don’t do that: greet_friends(“Barry”) Huh, not what we expected, right? Well, what’s going on here? This happens because
strings are iterable, the for loop will go
over each letter of the string and do the
operation we asked it to do, which in this case,
print a greeting. Depending on what
you’re trying to do, you may actually want to iterate through the
letters of a string. But in this case, we don’t. So to sum it up, if you get an error that a
certain type isn’t iterable, you need to make
sure the for loop is using a sequence of
elements and not just one, and if you find your code
iterating through each letter of a string when you want it to do it for the whole string, you probably want to have that string be a part of a list. We’ve now learned how to write
while loops and for loops. You might remember, for loops are best when you want to iterate over a known sequence of
elements but when you want to operate while a
certain condition is true, while loops are the best choice. Next up, we’ve got a super
useful cheat sheet for you that puts all this into
one handy resource. After that, head over to the practice quiz to test your knowledge and check
in on how you’re doing.

Reading: Loops Cheat Sheet

Reading

Practice Quiz: Practice Quiz: For Loops

How are while loops and for loops different in Python?

Fill in the blanks to make the factorial function return the factorial of n. Then, print the first 10 factorials (from 0 to 9) with the corresponding number. Remember that the factorial of a number is defined as the product of an integer and all integers before it. For example, the factorial of five (5!) is equal to 12345=120. Also recall that the factorial of zero (0!) is equal to 1.

Write a script that prints the first 10 cube numbers (x**3), starting with x=1 and ending with x=10.

Write a script 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.

The retry function tries to execute an operation that might fail, it retries the operation for a number of attempts. Currently the code will keep executing the function even if it succeeds. Fill in the blank so the code stops trying after the operation succeeded.

Recursion (optional)


Video: What is recursion? (Optional)

Recursion is the repeated application of the same procedure to a smaller problem. It can be used to tackle complex problems by reducing them to simpler ones.

Here is a simple example of a recursive function in Python:

def factorial(n):
  if n < 2:
    return 1
  else:
    return n * factorial(n - 1)

This function calculates the factorial of a number. The factorial of a number is the product of all the positive integers less than or equal to that number. For example, the factorial of 5 is 120, because 120 is the product of 1, 2, 3, 4, and 5.

The factorial function works by calling itself recursively. In the base case, when n is less than 2, the function simply returns 1. In the recursive case, the function returns n multiplied by the factorial of n – 1. This creates a loop, where the function keeps calling itself until it reaches the base case.

Here is an example of how to use the factorial function:

>>> factorial(5)
120

Recursion can be a powerful tool for solving problems, but it is important to use it carefully. Recursive functions can be difficult to debug, and they can also lead to stack overflows if they are not implemented correctly.

Here are some tips for using recursion:

  • Use recursion when you have a problem that can be broken down into smaller, self-similar problems.
  • Make sure that your recursive function has a base case. This is the case where the function does not call itself recursively and instead returns a simple result.
  • Be careful of stack overflows. If your recursive function calls itself too many times, it can overflow the stack and cause your program to crash.

If you are unsure whether or not to use recursion, it is always best to consult with a more experienced programmer.

Recursion is a programming technique in which a function calls itself. This can be used to solve problems that can be broken down into smaller, self-similar problems.

For example, let’s say we want to write a function to calculate the factorial of a number. The factorial of a number is the product of all the positive integers less than or equal to that number. For example, the factorial of 5 is 120, because 120 is the product of 1, 2, 3, 4, and 5.

We can write a recursive function to calculate the factorial of a number as follows:

def factorial(n):
  if n == 0:
    return 1
  else:
    return n * factorial(n - 1)

This function works by calling itself recursively. In the base case, when n is 0, the function simply returns 1. In the recursive case, the function returns n multiplied by the factorial of n – 1. This creates a loop, where the function keeps calling itself until it reaches the base case.

Here is an example of how to use the factorial function:

>>> factorial(5)
120

Recursion can be a powerful tool for solving problems, but it is important to use it carefully. Recursive functions can be difficult to debug, and they can also lead to stack overflows if they are not implemented correctly.

Here are some tips for using recursion:

  • Use recursion when you have a problem that can be broken down into smaller, self-similar problems.
  • Make sure that your recursive function has a base case. This is the case where the function does not call itself recursively and instead returns a simple result.
  • Be careful of stack overflows. If your recursive function calls itself too many times, it can overflow the stack and cause your program to crash.

If you are unsure whether or not to use recursion, it is always best to consult with a more experienced programmer.

Here are some other examples of problems that can be solved using recursion:

  • Finding the Fibonacci sequence
  • Traversing a tree or graph
  • Sorting a list
  • Searching for an element in a list

If you are interested in learning more about recursion, there are many resources available online and in libraries.

Welcome back. How are you
feeling after the last quiz? We’re starting to learn some pretty cool things that
we could do in our code. Who knew loops can
be so fascinating? We’ve now discovered two looping techniques
that we could use in Python: while
loops and for loops. We use while loops
when we want to do an operation repeatedly while a certain condition is true. We use for loops when we want to iterate over the
elements of a sequence. Now, we’re going to check out a third technique
called recursion. But before we dive in, you may have noticed
that this video is marked as optional. That’s because while recursion is a very common technique used
in software engineering, it’s not used that
much in automation. Still, we think it’s valuable
for you to know about recursion and to have an
idea of how to use it. You may see it in code
written by others or you may face a problem where recursion is the best
way to solve it. So while the next few
videos are marked as optional and you won’t be
graded on their content, it’s still super valuable stuff. Of course, feel free to skip
them if you’d just rather focus on concepts you’ll be
graded on. Let’s dive in. Recursion is the
repeated application of the same procedure to
a smaller problem. Have you ever played with
a Russian nesting doll? They are a great visual
example of recursion. Each doll has a smaller
doll inside it. When you open up the doll to
find the smaller one inside, you keep going until you reach the smallest doll
which can’t be opened. Recursion lets us tackle complex problems by reducing the problem to a simpler one. Take our Russian nesting dolls, all nested inside each other. Imagine we want to find out how many dolls
there are in total. We would need to open each
doll one by one until we got to the last one and then count how many
dolls we’ve opened. That’s recursion in action. Here’s another example with
a more complex problem. Imagine you’re in a
line of people and you want to know how many
people are in front of you, and let me tell you I
can’t stand long lines. Anyway, if the line is long, it might be hard to
count the people without leaving the line and
losing your place. Instead you can ask
the person in front of you how many people
are in front of them. Since this person will be in
the same situation as you, they’ll have to ask
the same question to the person in
front of them and so on and so on
until the question reaches the first
person in the line. This person can confidently reply that there are no
people in front of them. So then the second person
in line can reply one, the person behind
them replies two, and so on until the
answer reaches you. Okay. I know the chances are
pretty small that all of those people would
play along just so you can know where you are in line, but it’s a useful way to
visualize how recursion works. How does this translate
into programming? Well, in programming,
recursion is a way of doing a repetitive task by having
a function call itself. A recursive function
calls itself usually with a modified parameter until it reaches a specific condition. This condition is
called the base case. In our earlier examples, the base case would be the smallest Russian doll or the person at the
front of the queue. Let’s check out an example of a recursive function to understand what we’re talking about. Here, we’re defining a
function called factorial. At the beginning of the function, we have a conditional block
defining the base case,
[on screen] def factorial(n): where n is smaller than 2.
[on screen] if n < 2: It simply returns the value 1.
[on screen] return 1 After the base case, we have a line where the
factorial function is calling itself with n minus 1.
[on screen] return n * factorial(n-1) This is called the
recursive case. This creates a loop. Each time the
function is executed, it calls itself with a smaller number until it
reaches the base case. Once it reaches the base case, it returns the value 1. Then the previously called function multiplies that by two and the previously called
function multiplies it by three and so on. This loop will keep going until the first factorial function called returns the desired
result. It’s a bit complex. Let’s add a few
print statements to see exactly how this works. print(“Returning ” + str(result) + “ for factorial of ” + str(n))
return result
So here we can see the function kept calling itself until
it reached the base case. After that, each function
returned the value of the previous function
multiplied by n until the original
function returned. Cool, huh? Next up, we’re going to check out
some more examples of when to use recursion and when
it’s best to avoid it.

The function sum_positive_numbers should return 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. Fill in the gaps to make this work:

def sum_positive_numbers(n):
    # The base case is n being smaller than 1
    if n < 1:
        return 0

    # The recursive case is adding this number to 
    # the sum of the numbers smaller than this one.
    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

Whoohoo! You’ve just written your first recursive function.
Well done!

Video: Recursion in Action in the IT Context

Recursive functions are a powerful tool that can be used to solve problems that would be difficult or cumbersome to solve with iterative loops.

Recursive functions work by calling themselves, passing in a different value each time. This process continues until a base case is reached, at which point the function returns a value. The value returned from the base case is then used as the return value for the previous call, and so on, until the original call returns.

Recursive functions are particularly well-suited for working with recursive structures, such as directories and user groups.

Here are some examples of how recursive functions can be used to solve IT-related problems:

  • Calculating the number of files in a directory and its subdirectories
  • Listing all human users that are part of a given group, including users that are members of nested groups
  • Traversing a tree data structure and performing some operation on each node

Important considerations:

  • Recursive functions can be difficult to debug, so it is important to test them thoroughly.
  • Recursive functions can be inefficient if the recursive structure is very deep.
  • Some languages have a limit on the number of recursive calls that can be made.

Conclusion:

Recursive functions are a powerful tool that can be used to solve a variety of problems. However, it is important to be aware of the potential pitfalls before using them.

Recursion is a programming technique in which a function calls itself. This can be used to solve problems that can be broken down into smaller, self-similar problems.

Here is an example of a recursive function in Python:

def factorial(n):
  if n == 0:
    return 1
  else:
    return n * factorial(n - 1)

This function calculates the factorial of a number. The factorial of a number is the product of all the positive integers less than or equal to that number. For example, the factorial of 5 is 120, because 120 is the product of 1, 2, 3, 4, and 5.

This function works by calling itself recursively. In the base case, when n is 0, the function simply returns 1. In the recursive case, the function returns n multiplied by the factorial of n – 1. This creates a loop, where the function keeps calling itself until it reaches the base case.

Here is an example of how to use the factorial function:

>>> factorial(5)
120

Recursion can be used to solve a variety of problems in the IT context. Here are a few examples:

  • Calculating the number of files in a directory and its subdirectories. This can be done by writing a recursive function that takes a directory as input and returns the number of files in that directory and all of its subdirectories. The base case would be a directory with no subdirectories. For this case, the function would simply return the number of files in the directory. The recursive case would be calling the recursive function for each of the contained subdirectories. The return value of a given function call would be the sum of all the files in that directory plus all the files in the contained subdirectories.
  • Listing all human users that are part of a given group. This can be done by writing a recursive function that takes a group as input and returns a list of all the human users that are part of that group and any subgroups. The base case would be a group that only includes users. For this case, the function would simply return the list of users in the group. The recursive case would be calling the recursive function for each of the contained groups. The return value of a given function call would be the list of users in that group plus the list of users in any subgroups.

Recursion is a powerful tool for solving problems in the IT context, but it is important to use it carefully. Recursive functions can be difficult to debug, and they can also lead to stack overflows if not implemented correctly.

Here are some tips for using recursion:

  • Use recursion when you have a problem that can be broken down into smaller, self-similar problems.
  • Make sure that your recursive function has a base case. This is the case where the function does not call itself recursively and instead returns a simple result.
  • Be careful of stack overflows. If your recursive function calls itself too many times, it can overflow the stack and cause your program to crash.

If you are unsure whether or not to use recursion, it is always best to consult with a more experienced programmer.

By now you’ve seen what
a recursive function looks like, how to write a base case and
the recursive case. You might be wondering why do we need
recursive functions if I can just use a for or while loop? Well, solutions to some specific
problems are easier to write and understand when using recursive functions. A lot of math functions
like the factorial or the sum of all the previous
numbers are good examples of this. If a math function is already
defined in recursive terms, it’s straightforward to just write
the code as a recursive function. But it’s not just about math functions. Let’s check out a couple of examples
of how this could help an IT specialist trying to automate tasks. Let’s say that you need to write a tool
that goes through a bunch of directories in your computer and calculates how
many files are contained in each. When listing the files inside a directory,
you might find subdirectories inside them and you’d want to count the files
in those subdirectories as well. This is a great time to use recursion. The base case would be a directory
with no subdirectories. For this case, the function would
just return the amount of files. The recursive case would be
calling the recursive function for each of the contained subdirectories. The return value of a given function call
would be the sum of all the files in that directory plus all the files in
the contained subdirectories. A directory of files that can contain
other directories is an example of a recursive structure. Because directories can contain
subdirectories that contain subdirectories that contain subdirectories, and so on. When operating over recursive structure, it’s usually easier to use recursive
functions than for or while loops. Another IT-focused example of a recursive
structure is anything that deals with groups of users that can
contain other groups. We see this situation a lot when using
administrative tools like active directory or LDAP. Say your group management software allows
you to create groups that have both users and other groups as their members. And you want to list all human users
that are part of a given group. Here you would use a recursive
function to go through the groups. The base case would be a group that
only includes users listing all of them. The recursive case would mean going
through all the groups contained listing all the users in them and then listing
any users contained in the current group. It’s important to call out that in some
languages there’s a maximum amount of recursive calls you can use. In Python by default, you can call a recursive function
1,000 times until you reach the limit. That’s fine for
things like subdirectories or user groups that aren’t
thousands of levels deep. But it might not be enough for mathematical functions like
the ones we saw in the last video. Let’s go back to our factorial
example from the last video and try to call it with n equals 1,000. Factorial(1000), See that error? It’s telling us that we’ve reached
the maximum limit for recursive calls. So while you can use recursion in
a bunch of different scenarios, we only recommend using it when you need
to go through a recursive structure that won’t reach a thousand nested levels. All right, we’ve just added recursion
to your growing scripting tool box. They’re ready for
you whenever the situation calls for it.

Which of the following scenarios would benefit the most from using a recursive function to solve the problem?

You need to create a family tree, showing several generations of your ancestors, with all of their children.

Great job! You’re getting the concept of recursion and when it’s a better solution than the traditional looping techniques.

Reading: Additional Recursion Sources

Reading

Practice Quiz: Recursion

What is recursion used for?

Which of these activities are good use cases for recursive programs? Check all that apply.

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.

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?

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.

Module Review


Video: Loops Wrap Up

This module covered three different ways to tell a computer to do an action repetitively: while loops, for loops, and recursion.

  • While loops: While loops are used when we want to do an operation while a certain condition is true or alternatively until it becomes false.
  • For loops: For loops are used when we want to iterate over the elements of a sequence or a range of numbers.
  • Recursion: Recursion is used when the problem is best solved in smaller steps and then combining those steps towards a larger solution.

When to use each type of loop:

  • While loops: Use a while loop when you need to execute a block of code until a certain condition is met. For example, you could use a while loop to read a file until the end of the file is reached, or to keep asking a user for input until they enter a valid value.
  • For loops: Use a for loop when you need to iterate over a sequence of elements. For example, you could use a for loop to print all of the items in a list, or to perform a calculation on each element in a list.
  • Recursion: Use recursion when the problem can be broken down into smaller subproblems of the same type. For example, recursion can be used to calculate the factorial of a number, or to traverse a tree data structure.

Conclusion:

Loops are a powerful tool that can be used to automate repetitive tasks and to solve complex problems. By understanding the different types of loops and how to use them, you can write more efficient and robust code.

[MUSIC] Wow, we’ve come a long way and
you’ve learned a lot already. Now’s a good time to stop and
give yourself a big pat on the back. In this module, we’ve looked at ways we can use to tell
a computer to do an action repetitively. Python gives us three different ways to
perform repetitive tasks while loops, for loops, and recursion. We use while loops when we want to do
an operation while a certain condition is true or
alternatively until it becomes false. We use for loops when we want to iterate
over the elements of the sequence or a range of numbers. And we use recursion when the problem
is best solved in smaller steps and then combining those steps
towards a larger solution. If you’re still not sure which
is the best tool to choose for a specific problem don’t worry,
that’s normal. As you keep practicing your automation
skills, choosing between one option and another will become natural. So next time you find yourself doing
the same or similar things over and over again, that’s your call to see if you
can use a loop to get your computer to do the work for you. Up next it’s test time again,
with the next graded assessment. Like always remember you can take as
much time as you need before taking the assessment. Go at your own pace, review everything
we’ve covered, and practice the examples. So there’s no chance loops will
ever throw you for a loop.

Video: In Marga’s Words: How I Got Into Programming

The speaker is a software developer at Google who taught herself how to code. They started coding as a kid by creating a simple text game, and then studied electronic engineering in college. After college, they got a job as an IT support specialist and then as a software developer. They have been working at Google for seven years.

The speaker says that they have faced more opportunities for growth than obstacles in their career. For example, when they needed to learn a new programming language or technology, they saw it as an opportunity to grow their skills.

The speaker is passionate about programming and has always kept expanding their horizons by learning new things.

[MUSIC] I’m the youngest of four siblings, and my family has always had a culture of
sharing our passions with each other. So when I was a kid, one of my older
brothers brought a computer to our home. And he encouraged me to
tinker with the computer to participate in the online network. And I started coding and
playing around with the computer. And I got really excited. So one of the things I did as a kid with
my computer was get it to do a small text game, kind of a Choose Your Own Adventure
book, but as a computer text game. It was really simple but it got me really excited into being able
to get the computer to do what I wanted. I studied electronic
engineering back in Argentina. I did not study computer science. I taught myself how to
program on my own time. But then I always worked in IT. I never worked as an electronic engineer. I got my first job as an IT support
specialist, but it was just by chance. I only got it because a friend of
mine called me on the phone and asked me whether I knew someone that could
do support for this small company that was looking for someone that could
help them with their IT stuff. And I was like, yeah,
I could be that person. And my only background was to
having done the IT support for my family on my home computer,
my mother’s computer. I had no formal education,
no formal training doing IT support, but I felt like I could do the job,
so I took it. And I learned a lot doing that work,
and then I kept learning more skills. I learned how to program for
reals not just text games. And eventually, I got another job as
a software developer and I kept learning, kept learning new programming languages,
new techniques, new frameworks. So I always kept expanding my
horizons because I feel really passionate about programming in general. I’ve been working for
Google for seven years. I’m originally from Argentina, but
I moved to Germany seven years ago. When I look back to my career in IT, I wouldn’t say that I
really face big obstacles. Mostly I would say I faced
opportunities for growth. So if I needed to learn a new
programming language or I needed to learn new technologies,
they were all opportunities for growth.

Quiz: Module 3 Graded Assessment

Fill in the blanks of this code to print out the numbers 1 through 7.

The show_letters function should print out each letter of a word on a separate line. Fill in the blanks to make that happen.

Complete the function digits(n) that returns how many digits the number has. For example: 25 has 2 digits and 144 has 3 digits. Tip: you can figure out the digits of a number by dividing it by 10 once per digit until there are no digits left.

This function prints out 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). Fill in the blanks so that calling multiplication_table(1, 3) will print out: 1 2 3 2 4 6 3 6 9

The counter function counts down from start to stop when start is bigger than stop, and counts up from start to stop otherwise. Fill in the blanks to make this work correctly.

The even_numbers function returns a space-separated string of all positive numbers that are divisible by 2, up to and including the maximum that’s passed into the function. For example, even_numbers(6) returns “2 4 6”. Fill in the blank to make this work.

The following code raises an error when executed. What’s the reason for the error?

What is the value of x at the end of the following code?

What is the value of y at the end of the following code?

How does this function need to be called to print yes, no, and maybe as possible options to vote for?