5.3: 🔁 For Loops

Topic

5.3: 🔁 For Loops

Topic Progress:

When you’re writing code, there may be times where you want to repeat a task multiple times, instead of rewriting the same chunk of code over and over, we can use a loop!

Everything inside of a loop is repeated over and over until you tell the loop to stop. There are two types of loops in python, for loops and while loops:

  • For loops stop when you’ve repeated the loop a certain number of times
  • While loops stop when a boolean (True or False) condition is met

Both types of loops have their own strengths but they can both be used interchangeably 

For Loops

For loops are the most commonly used loop. We use for loops when we already know how many times we want to repeat the loop.

For example, we can use a for loop to loop through and print every item in a list 

We can also have nested loops. This is when you have loops inside of other loops. 

For example, we can loop through each word inside of a list then for each word, we can print each letter of that word.

We can also use range() to repeat a loop a specific number of times.

Note: because counting in python begins at 0, a for loop using range(x) will begin at 0 and go up to x-1. So the code below for range(10) will print out 10 numbers from 0-9.

@

Not recently active