Wednesday, August 24, 2016

Dissecting a Loop


Okay! The last thing with this loop thing is a bit confusing. Explain it!

I agree. So, let's try to see how it works, step by step.

Here's this loop:
for n in range(1, 21):
    print(n, "squared is", n * n)

First, let me remind you again, that when we use loops, if statements, or create our own functions (wait for them), we use statement followed by semicolon. Consider our loop here:

for n in range(1, 21):
What must follow is a block of code (statements) that will be repeated the number of times specified in the range(1, 21).
Step 1
Assign first number from the range (1) to variable n. In other words now n = 1.
Step 2
Check if n is grater than 20 (remember 21 - 1 is the last number in the range). NO! it is still in the range specified. Then proceed to step 3.
Step 3
Execute all statements in the block of code (indented by 4 spaces). We have only one statement here:
print(n, "squared is", n * n)
This will print value stored in variable n (comma means make a space and print the next item: squared is (comma means make a space and print next item which is value of multiplying n by n). That will print the following:

1 squared is 1
Step 4
Since current value of variable n is still in range (between 1 and 20), Python jumps back to for statement and uses the next value in the range (2) and assigns it to variable n. Now n = 2.

Step 5
The variable n is still in range, then it executes all statement in the block of code:

print(n, "squared is", n * n)

Now n = 2, so this print statement displays the following (n * n = 2 * 2 = 4):

2 squared is 4

Variable n = 2 that is still in range (1 - 20) jump back to for n statement. There, for statements assigns next value in range to variable n. Now, n = 3.

Step 6
The variable n is still in range, then it executes all statement in the block of code:

print(n, "squared is", n * n)

Now n = 3, so this print statement displays the following (n * n = 3 * 3 = 9):

3 squared is 9

Variable n = 2 that is still in range (1 - 20) jump back to for n statement:


Round and round it goes like that, until variable n is no longer in range (1 - 20). Then it leaves this block of indented statements and proceed to the next line of code. There is no next line of code in our little program. Python terminates the program as our list of task is now completed!

Problem Solving

Write a code that displays something like this:

pi@tron ~ $ python3 loop-again.py 

Using variable i in the loop.
Let's go!

Iteration 0 - variable i = 0
Iteration 1 - variable i = 1
Iteration 2 - variable i = 2
Iteration 3 - variable i = 3
Iteration 4 - variable i = 4
Iteration 5 - variable i = 5

Program terminates! Bye!
pi@tron ~ $