Site icon Analytics4All

Python: Loops


One of the most useful functions of a computer is its ability to repeat tasks over and over without tiring or complaining. How do we get our computers to repeat these tasks? Loops


Before we can learn about loops though, we need to discuss Whitespace:

One of the main features of Python is that it uses whitespace. Indents (the whitespace) are how Python knows which lines of code belong to loops, etc.

In the code example above, we are running a for loop iterating 1 – 5. Notice the print i statement is executed all five times in the loop, while print “hello” does not execute until the loop is over. This is because print i is indented (uses whitespace)

For Loop

Probably the first loop everyone learns in programming, For loops are simple to construct and understand. In the whitespace example I created a very basic for loop. To understand what is happening:

Notice in the example below, the numbers a assigned to “i” in the order they are in the list. Numeric order means nothing.

In fact, you don’t even need numbers:

Try your code in our online Python console:  

For Range ()

While the above for loops work, they have a serious limitations. What if you wanted to do 1000 iterations? You would have to  type every number from 1 to 1000 in the square brackets. That would be tedious.

So, to avoid that nightmare, we have the Range() function.

ln[7] we use range(0,3). Our output is 0,1,2. Note it does not go to 3. The syntax for range() is as follows:

range(start, stop, step)

note ln[8] counts by 2 since the step was set to two.

While Loop

The while loop works by counting from the bottom. While you can find discussions all over the web as to why you would use one over the other, the truth is, with a little programming judo, you can accomplish the same goals with either loop.

Here is the syntax for a while loop:

You can add a break into the loop to end it based on a condition, below when x = 3, the loop will break – or end

You can also add the continue argument

you can also use an else argument

Try your code in our online Python console:  

If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT

Last Page: Tuples and Sets

Next Page: Functions

Back to Python Course: Course

Exit mobile version