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!

Python List Comprehension

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!

Python list comprehensions provide a concise way for creating lists. It consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses: [EXPRESSION for ITEM in LIST <if CONDITIONAL>].

The expressions can be anything - any kind of object can go into a list.

A list comprehension always returns a list.

Python For Loop

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!

A Python for loop can be used to iterate over a list of items and perform a set of actions on each item. The syntax of a for loop consists of assigning a temporary value to a variable on each successive iteration.

When writing a for loop, remember to properly indent each action, otherwise an IndentationError will result.

The Python continue 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 Python, the continue keyword is used inside a loop to skip the remaining code inside the loop code block and begin the next loop iteration.

Python for Loops

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!

Python for loops can be used to iterate over and perform an action one time for each element in a list.

Proper for loop syntax assigns a temporary value, the current item of the list, to a variable on each successive iteration: for <temporary value> in <a list>:

for loop bodies must be indented to avoid an IndentationError.

Python Loops with range().

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 Python, a for loop can be used to perform an action a specific number of times in a row.

The range() function can be used to create a list that can be used to specify the number of iterations in a for loop.

Infinite Loop

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!

An infinite loop is a loop that never terminates. Infinite loops result when the conditions of the loop prevent it from terminating. This could be due to a typo in the conditional statement within the loop or incorrect logic. To interrupt a Python program that is running forever, press the Ctrl and C keys together on your keyboard.

Python while Loops

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 Python, a while loop will repeatedly execute a code block as long as a condition evaluates to True.

The condition of a while loop is always checked first before the block of code runs. If the condition is not met initially, then the code block will never run.

Python Nested Loops

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 Python, loops can be nested inside other loops. Nested loops can be used to access items of lists which are inside other lists. The item selected from the outer loop can be used as the list for the inner loop to iterate over.

  1. 1
    How do we use code to tell a computer this: “Create a variable and call a function 15 times”? We could write it out 15 times: create a variable call a function create a variable call a function …
  2. 2
    When we give instructions once and tell the computer how many times to repeat them, we are using a for loop, or a count-controlled loop. It executes a set of instructions for a specified numb…
  3. 3
    What if you approached tile-placing another way: you don’t know how many tiles to place, but you know when to stop. How could you communicate this type of command to a computer? Give it the instruc…
  4. 4
    There’s one more way to give looping instructions to a computer. We define a sequence of desired tile colors (a list), and tell the computer to repeat the instructions for each item in the sequen…
  5. 5
    Let’s combine all that we’ve learned so far: * variables, operators, and data types * functions and control flow * lists and loops Examples of for and while loops are provided below in JavaScript….
  6. 6
    Well done! Loops are commonly used in programming because they save time, reduce error, and are easy to read. Being comfortable with each type of loop will make you a better programmer. In review: …
  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…