Loops
Loops are structures that let you repeat Python code over and over. Learn how to read loops and write them to solve your own problems.
StartKey Concepts
Review core concepts you need to learn to master this subject
break
Keyword
Python List Comprehension
Python For Loop
The Python continue
Keyword
Python for
Loops
Python Loops with range()
.
Infinite Loop
Python while
Loops
break
Keyword
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
- 1Suppose 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(…
- 2In 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…
- 3Previously, 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…
- 4We’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…
- 7We 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…
- 8We 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 …
- 9Let’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…
- 10Let’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…
What you'll create
Portfolio projects that showcase your new skills
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory