Python Tutorial #3 - The for-LoopsteemCreated with Sketch.

in #programming7 years ago

The for-Loop

Today, we are gonna look at loops. What the Hell are loops?, some of you might ask now.
Loops are responsible for repeating a part of the code until a specific condition which we declare is met.
In Python, there are two types of loops: The for-Loop and the while-Loop.
We are using the for-Loop now.

In Python, the for-Loop is easier to use than in other programming languages. Let's look at it.

for n in range(0, 11):
        print(n)

The first thing to be mentioned is that in Python some code needs to be indented.
It's specifically the code that comes in functions or loops. You can make an indentation with a tab.

In the beginning, we start our for-Loop with the keyword for. Next, we name the element the loop uses.
To understand that, you need to know that the for-Loop can be a shortcut for handling each element in a given list.
The function range(0, 11) returns a list of all numbers from 0 to 10. If we would see it, it would look like this: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. It's important to know that the last number of the range functions output is always 1 less then the actual number you entered.

In each run of our for loop, it takes the next element of the range function we declared as n (you can name this however you want) and executes the code with n defined as the current element of the list.
In this case, print(n) just prints out the current number. If there are no more elements in the list the loop ends.

If we execute this we can see the numbers 0 to 10 being printed out, stating that everything worked fine.

If we would do something like

list = ['a', 'b', 'c']

for element in list:
       print(element)

the output would be a b c.

That's the end of todays tutorial! If you have questions please write them in the commentaries!
In the next part we will deal with the while-Loop.

Sort:  

Following!
I hope you do tutorials about advanced concepts as well.

I will for sure! After we finished the basic parts of Python we will get to the more complex concepts. I'm glad you like my content, thank you for your support!

Coin Marketplace

STEEM 0.25
TRX 0.19
JST 0.036
BTC 91660.56
ETH 3295.97
USDT 1.00
SBD 3.83