PieceOfAPie
PieceOfAPie
  • Home
  • Tutorials
  • More
    • Home
    • Tutorials
  • Home
  • Tutorials

For Loops

 Previous Lesson


In Python, sometimes, you might have to repeat some things many times and sometimes, just copy pasting a set of lines might be really taxing. So, we have something called for loops. With for loops, you can repeat a set of lines however many times you want. Here is an example below.

  •  For Loop Example

You can write a for loop like this:

  • for variable in range(number):
  •    # The set of lines you want to repeat


The variable in the for loop keeps track of the number of times you have ran the for loop. In the previous example, that variable was counter. Once that variable is equal to the range (The number of times you want to repeat the for loop), the for loop ends. 

 

Here is the basic syntax for the range:

  • The range is a basic function in Python that allows you us to start at a certain value, stop at a certain value, and increment by a certain value. 


  • When there is only one number in the range, then it shows that the starting value is 0, the stopping value is the number, and the incrementation value is 1
    •  Example


  • When there are two numbers in the range, then it shows that the starting value is the first number, the stopping value is the second number and the incrementation value is 1.
    •  Example


  • When there are three numbers in the range, then it shows that the starting value is the first number, the stopping value is the second number, and the incrementation value is the third number.
    •  Example


Make sure to write a colon after the for loop as shown in the example and also indent the following lines you want repeated.

For Loops Exercise

Make a program using for loops that gives an output like this:

1

1 1

1 1 1

1 1 1 1

The program should ask the user how many times it wants the for loop to run and implement the response in the for loop.


Challenge: 

Make a similar program using for loops that gives an output like this:

1

1 2

1 2 3

1 2 3 4

Next Lesson

While Loops

Copyright © 2024 PieceOfAPie - All Rights Reserved.

Powered by GoDaddy

This website uses cookies.

We use cookies to analyze website traffic and optimize your website experience. By accepting our use of cookies, your data will be aggregated with all other user data.

Accept