Working With Loops In Python

in STEMGeeks2 months ago

Even though our last article concentrated on working with Lists in your Python code, at the very end we introduced you to a For Loop in Python which allowed us to move through all the values in the List.

We only briefly touched on the subject, so this article is going to move a lot further in depth and show you how you can use Loops within your Python code. Python has two main types of Loops you can use, they are :

  • For Loops, which we used in our previous article and
  • While Loops

For Loops


A For Loop in usually used to iterate(or loop) over a specific set of data. In the previous article we had a List of values which we then used a For Loop to work through. The For Loop can then execute a set of statements for each of the items in the set of data.

If we take the code we used in our previous article we had the List called total_savings. We used the For Loop to go through each of the values in the list assigning these values to the variable of "i". The second line of the Loop is the statement that is performed over each of the items, in this instance adding the value to the total variable.

for i in total_savings:
  total += int(i)

To see some more examples, open the interactive shell in Python and see how the following For Loops work. In the first example, we have created the variable named different_fruits which we have added a list of different fruit names. The loop starts by assigning each of the values in the List to the x variable, and then simply uses the print() function to output each of the values to the screen:

>>> different_fruits = ["apples", "bananas", "cherrys"]
>>> for x in different_fruits:
...   print(x)
...
apples
bananas
cherrys

The following examples, shows that we don't even need to be using a list to create a For Loop. In each of the examples, we have added what is going to be looped through in the "for" statement of the Loop. As you can see in the first example, we have simple added the String "fruits" which then outputs each of the letters in the word. The second example then using the range() function. The range function simply provides a List of numbers from 1 to what ever the number in the brackets, in our example 10. The Loop then outputs all the details below:

>>> for x in "fruits":
...   print(x)
...
f
r
u
i
t
s

>>> for x in range(10):
...   print(x)
...
0
1
2
3
4
5
6
7
8
9

If you ever have a situation where you are still trying to decide what your code will include as the statement in your For Loop. You need to make sure it does something. In the example below, which adds a simple List directly into the first line of the For Loop, but as you can see the statement being run is the "pass" statement, which doesn't do anything but does not cause an error in your code:

>>> for x in [1, 2, 3]:
...   pass
...

Nested Loops


There's no reason why you can't put a Loop inside a Loop. In the following example, we have added a List which has numbers added to provide order details for each of the different_fruits.

>>> orders= ["4", "8", "2"]
>>> different_fruits = ["apples", "bananas", "cherrys"]
>>>
>>> for x in orders:
...   for y in different_fruits:
...     print("Please order {} boxes of {}".format(x,y))
...
Please order 4 boxes of apples
Please order 4 boxes of bananas
Please order 4 boxes of cherrys
Please order 8 boxes of apples
Please order 8 boxes of bananas
Please order 8 boxes of cherrys
Please order 2 boxes of apples
Please order 2 boxes of bananas
Please order 2 boxes of cherrys

While Loops


While Loops work a little different as they will execute a set of statements as long as a condition is true. The easiest way to explain this is through our example below, where we have a variable "i" set to the number 1. The first line of the While Loop will perform a test to make sure that "i" is less than 6, and if it is, will perform the statements below. We print out the value of "i" and then we add 1 to the value of "i". If this last statement was not included the value of "i" would remain as 1 and the Loop would continue for ever and not stop until either the program was killed or the system it was running on was turned off:

>>> i = 1
>>> while i < 6:
...   print(i)
...   i += 1
...
1
2
3
4
5

Break and Continue


There may be some situations when you need to stop a loop due to a certain condition. Fortunately Python gives you a way to do this using the Break statement to completely stop the loop from running, or the Continue statement which will just stop the iteration of the Loop but continue with the remainder of the loop.

NOTE: The main way to use Continue and Break is by using an If Statement in Python to test a certain condition. We haven't shown you If Statements yet but will only be using the basic functionality for now.

The best way to show you how this is done is to use some examples. The first example we have below uses the Break statement. First we use the "if x == "n": statement to test if the letter is equal to "n". If this equals to true, then the break statement is used. As you can see from the output below the whole Loop then stops completely. The output only loops through the "b" and "a" of the Loop:

>>> for x in "banana":
...   if x == "n":
...     break
...   print(x)
...
b
a

Below we have a Continue statement where instead of only running the Loop for the first two characters, every character is run except for the letter "n".

>>> for x in "banana":
...   if x == "n":
...     continue
...   print(x)
...
b
a
a
a

This has been a bit of a quicker article but hopefully we've been able to make it clear how Loops can be used in Python. We'll keep going with our sample program in our next article and also provide a clear introduction to If Statements.

Found this post useful? Kindly tap the up vote button below! :)

About The Author


I am a DevOps Engineer, Endurance Athlete and Author. As a DevOps Engineer I specialize in Linux and Open Source Applications. Particularly interested in Search Marketing and Analytic’s, and is currently developing my skills in devops, continuous integration, security, and development(Python).

Posted with STEMGeeks

Sort:  

I love Python for loops as you can loop over just about anything very easily. In other languages it tends to be trickier. If you need to know which iteration you are on then we have the enumerate function.

!BEER

I know, it's so easy and will be using them a lot in the next from articles.
Regards Vince


Hey @run.vince.run, here is a little bit of BEER from @steevc for you. Enjoy it!

Learn how to earn FREE BEER each day by staking your BEER.