Key Concepts

Review core concepts you need to learn to master this subject

break Keyword

numbers = [0, 254, 2, -1, 3] for num in numbers: if (num < 0): print("Negative number detected!") break print(num) # 0 # 254 # 2 # Negative number detected!

In a loop, the break keyword escapes the loop, regardless of the iteration number. Once break executes, the program will continue to execute after the loop.

In this example, the output would be:

  • 0
  • 254
  • 2
  • Negative number detected!
Loops
Lesson 1 of 2
  1. 1
    Suppose we want to print() each item from a list of dog_breeds. We would need to use the following code snippet: dog_breeds = [‘french_bulldog’, ‘dalmatian’, ‘shihtzu’, ‘poodle’, ‘collie’] print(…
  2. 2
    In the previous exercise, we saw that we can print each item in a list using a for loop. A for loop lets us perform an action on each item in a list. Using each element of a list is known as _i…
  3. 3
    Previously, we iterated through an existing list. Often we won’t be iterating through a specific list, we’ll just want to do a certain action multiple times. For example, if we wanted to print out…
  4. 4
    We’ve iterated through lists that have a discrete beginning and end. However, let’s consider this example: my_favorite_numbers = [4, 8, 15, 16, 42] for number in my_favorite_numbers: my_favorit…
  5. 5
    We often want to use a for loop to search through a list for some value: items_on_sale = [“blue_shirt”, “striped_socks”, “knit_dress”, “red_headband”, “dinosaur_onesie”] # we want to check if the…
  6. 6
    When we’re iterating through lists, we may want to skip some values. Let’s say we want to print out all of the numbers in a list, unless they’re negative. We can use continue to move to the next i …
  7. 7
    We now have seen and used a lot of examples of for loops. There is another type of loop we can also use, called a while loop. The while loop performs a set of code until some condition is reach…
  8. 8
    We have seen how we can go through the elements of a list. What if we have a list made up of multiple lists? How can we loop through all of the individual elements? Suppose we are in charge of a …
  9. 9
    Let’s say we have scraped a certain website and gotten these words: words = [“@coolguy35”, “#nofilter”, “@kewldawg54”, “reply”, “timestamp”, “@matchamom”, “follow”, “#updog”] We want to make a…
  10. 10
    Let’s say we’re working with the usernames list from the last exercise: >>> print(usernames) [“@coolguy35”, “@kewldawg54”, “@matchamom”] We want to create a new list with the string “ please fol…
  11. 11
    Good job! In this lesson, you learned - how to write a for loop - how to use range in a loop - what infinite loops are and how to avoid them - how to skip values in a loop - how to write a while l…

What you'll create

Portfolio projects that showcase your new skills

Pro Logo

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory

Pro Logo