Home

For Loops

In programming, for loops are usually used to repeatedly loop through a sequence a number of times. The syntax for doing so is for i in range(start, stop, step). (Note: i is just a common letter used in coding, any letter or word is fine).

There are a few options for what you can put within the brackets (note: for loops can only take in integers, meaning no decimals). Putting a single integer will have a loop starting from 0 and go up in increments of 1 for n times.

Having two numbers will set a range where the loop begins at the first number and ends right when it gets second number by going up in increments of 1.

Lastly, putting three integers, sets the beginning, end, and the increment (start, stop, step).

More Details

In Python, it is also possible to iterate through a list with for i in listName. This results in the loop going through each index of the list.

It is also possible to have a for loop within another for loop which is called a nested for loop, which we will go through in a later lesson.

Try It Out!

Go to Replit
  • The user will enter a starting and ending number. Then iterate between those numbers by increments of 2.
  • Ask the user for a number, then ask for that many words to add to a list. Then print the contents of the list on separate lines.

Related Problems