create account

Working With Loops In Python by run.vince.run

View this thread on: hive.blogpeakd.comecency.com
· @run.vince.run ·
$12.40
Working With Loops In Python
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.](https://stemgeeks.net/hive-163521/@run.vince.run/user-input-and-lists-in-python)

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

<h2>For Loops</h2>
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
...
```

<h2>Nested Loops</h2>
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
```

<h2>While Loops</h2>
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
```

<h2>Break and Continue</h2>
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! :)***

<h2>About The Author</h2>
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](https://stemgeeks.net)
๐Ÿ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 452 others
properties (23)
authorrun.vince.run
permlinkworking-with-loops-in-python
categoryhive-163521
json_metadata{"tags":["coding","python","programming","development","pythonprogramming","runvincerun","stem"],"links":["https://stemgeeks.net/hive-163521/@run.vince.run/user-input-and-lists-in-python"],"app":"stemgeeks/0.1","format":"markdown","canonical_url":"https://stemgeeks.net/@run.vince.run/working-with-loops-in-python"}
created2021-03-22 02:37:42
last_update2021-03-22 02:37:42
depth0
children3
last_payout2021-03-29 02:37:42
cashout_time1969-12-31 23:59:59
total_payout_value6.286 HBD
curator_payout_value6.114 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length6,342
author_reputation198,279,292,951,249
root_title"Working With Loops In Python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id102,518,535
net_rshares16,421,791,530,111
author_curate_reward""
vote details (516)
@beerlover ·
<div class='pull-right'>https://files.peakd.com/file/peakd-hive/beerlover/yiuU6bdf-beerlover20gives20BEER.gif<p><sup><a href='https://hive-engine.com/?p=market&t=BEER'>View or trade </a> <code>BEER</code>.</sup></p></div><center><br> <p>Hey @run.vince.run, here is a little bit of <code>BEER</code> from @steevc for you. Enjoy it!</p> <p>Learn how to <a href='https://peakd.com/beer/@beerlover/what-is-proof-of-stake-with-beer'>earn <b>FREE BEER</b> each day </a> by staking your <code>BEER</code>.</p> </center><div></div>
properties (22)
authorbeerlover
permlinkre-runvincerun-working-with-loops-in-python-20210322t092545067z
categoryhive-163521
json_metadata{"app":"beerlover/2.0"}
created2021-03-22 09:25:45
last_update2021-03-22 09:25:45
depth1
children0
last_payout2021-03-29 09:25:45
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length523
author_reputation25,764,988,873,156
root_title"Working With Loops In Python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id102,522,996
net_rshares0
@steevc ·
$0.02
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
๐Ÿ‘  , , , , ,
properties (23)
authorsteevc
permlinkre-runvincerun-qqd65a
categoryhive-163521
json_metadata{"tags":["hive-163521"],"app":"peakd/2021.03.7"}
created2021-03-22 09:24:45
last_update2021-03-22 09:24:45
depth1
children1
last_payout2021-03-29 09:24:45
cashout_time1969-12-31 23:59:59
total_payout_value0.012 HBD
curator_payout_value0.011 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length212
author_reputation1,375,805,706,054,727
root_title"Working With Loops In Python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id102,522,986
net_rshares53,997,720,740
author_curate_reward""
vote details (6)
@run.vince.run ·
$0.33
I know, it's so easy and will be using them a lot in the next from articles.
Regards Vince
๐Ÿ‘  
properties (23)
authorrun.vince.run
permlinkqqebqu
categoryhive-163521
json_metadata{"app":"hiveblog/0.1"}
created2021-03-23 00:23:21
last_update2021-03-23 00:23:21
depth2
children0
last_payout2021-03-30 00:23:21
cashout_time1969-12-31 23:59:59
total_payout_value0.167 HBD
curator_payout_value0.167 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length90
author_reputation198,279,292,951,249
root_title"Working With Loops In Python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id102,538,510
net_rshares496,984,357,145
author_curate_reward""
vote details (1)