Project 12: Use of loops with ‘for’

--Originally published at TEC GDL 2016

After having covered the if statement and the use of else and elif within those statements I feel like I”m getting closer to actually do smarter things with my codes – not just tasks that I would easily be able to solve in my head.

Before I start explaining the logic behind ‘for’ loops – the topic of today’s blog post – I will once more explain how to create and use lists. This is necessary to bring back to mind because you need to store results of the loops you create somewhere.

Lists = Lists are containers of things that are organized from first to last that look like this:

courses = [Programming, Negotiation, Entrepreneurship]
schooldays = [Monday, Tuesday,Thursday,Friday]
(no school on Wednesday’s for me ;))

For further explanation have a look at an earlier blog post (click here) about basic types and their use.

Now to ‘for’ loops:

For loops are traditionally used when you have a piece of code you want to repeat ‘n’ number of times. There alternatively is also the ‘while’ loop that you are able to use within Python. These are rather considered when it comes to conditions to be met and I will be covering this in my NEXT blog post!

For loops run for a fixed amount of variables (compared to while loops that can theoretically run forever). Any object whose data can be represented in list form (also called ‘objects with an iterable method’) can be used in a ‘for’ loop. When for loops are used you are also able to create a list containing an amount of numbers (defined by the input) by using the “range” function.

Have a look at the following flow diagram to understand further how ‘for’ loops can be useful:

python_for_loop.jpg

Thus, a general syntax of a

Bildschirmfoto 2016-10-26 um 18.56.42.png
Bildschirmfoto 2016-10-26 um 18.55.27.png
Bildschirmfoto 2016-10-26 um 18.42.55.png
loop is:

for   variable   in   sequence:
         statement(s)
else:
         statement(s)

Have a look at the following code to understand further how ‘for’ loops are used:

Bildschirmfoto 2016-10-26 um 18.56.42.png

What you should see after executing this code:Bildschirmfoto 2016-10-26 um 18.55.27.png

When using an ‘else’ statement with a ‘for’ loop, the else statement is used once the loop has exhausted iterating the given list.
Have a look at the following to understand this:

Bildschirmfoto 2016-10-26 um 18.42.55.png

For additional uses of the ‘for’ loop visit this website:
https://wiki.python.org/moin/ForLoop
_
_____________________________________

That’s all there is to cover about ‘for’ loops. Make sure to visit my blog later today for more information on ‘while’ loops & nested loops!!

See ya later, aligator!
@tecjames

Sources:

https://learnpythonthehardway.org/book/ex32.html
https://wiki.python.org/moin/ForLoop
https://www.tutorialspoint.com/python/python_for_loop.htm
http://www.python-course.eu/python3_for_loop.php