# FOR LOOP

Life is cyclical. Nature is cyclical. Winter is replaced by spring, spring by summer, summer by autumn with a lot of rain and sleet, and then winter goes again, replaced by spring. Cycles. Time runs away: 1 a.m., and then suddenly 2 a.m., 3 a.m. ... afternoon, 1 p.m., 2 p.m., 3 p.m. ... Time goes by and it repeats again: one hour, two, three. Cycles, cycles, cycles.

Even our walking is cyclical. The first leg leaves the ground, swings forward from the hip, then it strikes the ground and the second goes. Repeat twenty times and you will reach the fridge. All is cyclical! Breakfast, lunch, dinner; work, work, work, salary, work, work, work, salary, work, work, work, salary, one leave a year. The first year goes like that, the second, the third.

Life is cyclical. We have already considered one example: days of the week. Cycle. Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday. Finished? Again! If we replace the days of the week by numbers, as we did it previously, then we'll get a permanent and recurring range of numbers:

1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3...

Thanks to the cycles and the constancy of events within the cycle, we can plan solid data processing algorithms. Water pierces rocks, cycles streamlines data. As water drop by drop, a cycle changes data command by command, creating new forms, structures and content.

The idea of cycles is to reach necessary result when repeating a certain action multiple times. Step by step to the fridge. By small steps, without extra efforts, but constantly, rhythmically, confidently moving towards the goal.

Repeating the actions again and again, we'll get sorted data.

What is multiplication? It is addition a number with itself as many times as it is indicated by multiplier. It's also a cycle!

2 * 4 = 2 + 2 + 2 + 2

"Multiple recurrence of a certain action in order to obtain a result": for 2 * 4 we'll repeat the action "add two to the result" four times.

To learn to plan and realize loops in programming (remark: it's called loops in coding, not cycles), we should develop the skill of finding small parts of the whole that have same meaning. In the example above 2 * 4, the small part is operation +2. Repeat it 4 times, and you'll get the result. It could be also operation +4, repeated 2 times.

We should make a habit to fragment data into pieces. A number can be fragmented into figures, a word - into characters. The task is to see, to understand, to guess, to invent formulas and algorithms of every processing part, so that we piece all fragmented parts together at the end of a calculation, at the end of the cycle.

We should learn to find dynamic patterns. Try to find a pattern and then answer the questions "Which rule combines all these numbers? What the number will replace the dot in the example below?

8 4 9 3 10 2 11 1 . 0

1. Each pair of numbers is predicted on the rule: the third number is the first plus one, the fourth is the second minus one, the fifth is the third plus one, and so on: 8 → 9, 4 → 3...

2. Desired number is 12.

Recall the program "Does the driver violate the rules?". What if we need to control the speed of three vehicles, not one. What about ten vehicles? Will we run the program each time? Well, ladies and gentlemen, it’s not quite convenient for us.

Right in this case, loops are appropriate to repeat the program three or ten times. And we'll just sit and enter the speed of the following vehicle. Mmmm, it's a dream job!

Loops are cool.

# TERMINO­LOGY

There won't be many terms, but they are still important. I will use them further in the text. It's something like a vocabulary that we'll deal with.

 Loop is a multiple recurrence of a certain action or actions in order to obtain a result.

For example, we can repeat our program about drivers, vehicles, speed and other things infinite number of times by using loops.

 A block of commands of the loop includes all the commands, indented with four spaces from the first character of a loop operator (in this case, from the character "f" in the "for" operator). The commands of the block will be executed sequentially, one by one. Meanwhile, the next command won't be executed until the previous one is implemented successfully. Also, the block of commands of the loop is called the loop body.

A block of commands of the loop is identified just like it would be identified if it belonged to a condition. The command that wasn't written according to the rules of the block, is considered a command outside of the loop. The loop is ended with the last command of the block, not with the wrong command:

For loop: Command 1 Command 2 Command 3 The last command of the block This string will be implemented only after the whole loop is finished.

 Iteration is one recurrence of the block of loop commands, from the first to the last.

For example, we can call the first week of the month "the first iteration": the range of the days from 1 to 7 inclusive. The next week and the next 1, 2, 3... 7 are the second iteration. The number of iterations is measured by the number of executions of all the loop commands.

 Loop counter is a special variable to which a programmer automatically and sequentially assigns iteration value.

Loop counter is a little more complicated than usual variable because of its automaticity. That's all right, we'll handle it.

 Iteration data is any fragmented set.

For example, the set of numbers 0, 1, 2, 3 is fragmented and relates to iteration data. We can easily dissect the set 0, 1, 2, 3 into the parts that form it: respectively, here goes 0, then 1, the next is 2 and the last is 3 - four different numbers that form the range.

Now think: whether a string variable is iteration data or not? For example, the variable that took the value "Hello"?

Yes, it is. Because the word "Hello" can be fragmented into separate sustained parts: the character "H", then - character "e", after that "l", "l", "o". Since every word or every set of characters consist of separate fragments - signs, every string variable relates to iteration data.

# FOR LOOP SYNTAX

The for loop is written in Python language as follows:

for COUNTER VARIABLE in range(NUMBER OF ITERATIONS): A block of loop commands

 range(x) is an integer array generator from 0 till x. I would like to emphasize that x is not inclusive. The last value of the range is (x - 1).

The next programs are equal. The program without loop:

print("Hello!") print("Hello!") print("Hello!") print("Hello!") print("Hello!")

The program with loop:

for i in range(5): print("Hello!")

The output of the programs is:

Hello! Hello! Hello! Hello! Hello!

Technically, it's simple: we set the number of iterations, wrote the command, repeated it and, voilà, got the result. Easy? Let's move on.

Now we are going to figure out how the loop counter i works. How will we do that? Just displaying its values on the screen:

for i in range(5): print(i)

The result is:

0 1 2 3 4

The values of range(5), i.e. 0, 1, 2, 3, 4 (till 5) were assigned to the loop counter sequentially. After that we displayed these values on the screen.

# DEALING WITH THE LOOP COUNTER

You should understand, remember and engrave on memory that loop counter can be used as a simple variable the value of which is assigned automatically by programming language. The same thing happens in other languages - Java, C++, Pascal.

Python allows to change the value of the loop counter in the loop body, but after one iteration the value from the range() will be assigned to it again.

Let's analyze:

for i in range(10): print("Value of i =", i, end="") i = i * 2 print(", changed value of i = i * 2 =", i)

The result is:

Value of i = 0, changed value of i = i * 2 = 0 Value of i = 1, changed value of i = i * 2 = 2 Value of i = 2, changed value of i = i * 2 = 4 Value of i = 3, changed value of i = i * 2 = 6 Value of i = 4, changed value of i = i * 2 = 8 Value of i = 5, changed value of i = i * 2 = 10 Value of i = 6, changed value of i = i * 2 = 12 Value of i = 7, changed value of i = i * 2 = 14 Value of i = 8, changed value of i = i * 2 = 16 Value of i = 9, changed value of i = i * 2 = 18

It's not hard to see that the first value of the loop counter i is always equal to the value of the range(10) function, that is sequentially 0, then 1, then 2, further 3, 4, 5, 6, 7, 8, 9.

 The parameter end="" after arguments of the first print() command: print("Value of i =", i, end="") sets end of line modifier. Empty quotes indicate that the modifier took the value emptiness. If we assign nothing to end="", then Python will output line break sign on the screen (it's equal to pressing the Enter key in text editors). In this case, each new print() will output text from a new line in the console of Python. We'll always set end="", as a parameter, when we need to continue the previous output with the next print(), i.e. display data in a line.

The value of the end="" modifier can be any character or even a string. For example:

print("This is ", end="changed end modifier")

Type that command and look what you've done.

But let's get back to loops.

 Among professional programmers it is customary to use the following identifiers for loop counters: i, j, o, p, k, l.

Again, it's not necessary to use these characters, but it will be nice if you make a habit to operate with them. At least because all decent textbooks, tutorials, material and documentation use these variable names. It would be more convenient, you know.

The range() function assigns the values of the loop counter. We can change its parameters if necessary, then the value of the loop counter will change with each iteration.

# RANGE() PARAME­TERS

Getting arrays of integers with range() is a good deal, moreover, range() is called a generator of numbers within a specified range. The syntax is:

range(x, y, z)

• x - initial value, the parameter isn't necessary;
• y - final value, the parameter is necessary;
• z - change interval (step) of counter variable, the parameter isn't necessary. The change step of the counter means the change of the range values, for example, if it is pointed out 3, then 3 will be add to the next values of the range: 0, 3, 6, 9...

 When x is not indicated (initial value), it is considered as 0. When z is not indicated (change interval), the values change at intervals of +1. The parameter z is always indicated when x > y and we need to get a downward range, i.e. from the largest to the smallest.

The output of numbers from 10 till 20 with a step 1 (parameter of the step isn't indicated):

for i in range(10, 20): print(i)

The result is:

10 11 12 13 14 15 16 17 18 19

Why is the last number 19, not 20?

Because range() generates numbers till specified value non-inclusive.

The output of numbers from 10 till 20 with a step 3 (parameter of the step is indicated):

for i in range(10, 20, 3): print(i)

The result is:

10 13 16 19

The task for you: generate a range of numbers where there will be necessarily two numbers - the day of the birth and the month in the right order (firstly goes the day, then the month somewhere in the range). For example, if you were born on the 15th of May (15.05), then one of the solutions is:

for i in range(15, 0, -5): print(i)

The result is the range with 15 and 5 in it:

15 10 5

Done? Then try to output the range of the numbers in a line by using the end="" modifier. And now it's time for "tricky" task!

Write a program that will output the range with 20 numbers with the following pattern:

8 4 9 3 10 2 11 1 12 0...

Solution:

for i in range(10): print(8 + i, 4 - i, "", end="")

The result is:

8 4 9 3 10 2 11 1 12 0 13 -1 14 -2 15 -3 16 -4 17 -5

You can have a different solution from presented here. It is not forbidden as long as your result is the same.

# CHECKING THE DRIVERS

The use of the loop counter isn't necessary in our loop. However, we must identify it in the title of the loop for i in range(x), but we don't have to process the counter inside the loop body.

Let's return to the poor drivers and our program that determines speeding fines. Now we are going to add one more requirement: user will enter at the beginning of the program how many vehicles must be checked. For example, 5, 10 or 25, or maybe 1, or even 0. Having received the value, our program will do everything needed brilliantly. We don't even have to change the code greatly.

 To repeat any code a few times, you should wrap it in the loop, that is, to form a loop block, having added four spaces before every line (having specified them as loop lines).

Our program before changes:

speed = int(input("Enter vehicle speed: ")) if (speed > 60 and speed <= 300): print("The driver violates the rules! Fine him, FINE!") elif (speed > 300): print("It isn't a plane. The entered speed is incorrect.") elif (speed == 0): print("The vehicle isn't moving. Like a stone. A stationary stone.") elif (speed < 0): print("The speed can't be negative. We are deeply sorry.") else: print("The driver doesn't violate the rules. The driver is good. Be like him.")

I'll enter one more variable countAuto. It will reflect the number of vehicles the speed of which we need to check.

countAuto = int(input("Enter the number of vehicles: "))

Now we are going to create a loop that will wrap the whole previous code:

for i in range(countAuto):

Here we'll use entered by the user number for the range() parameter. Therefore, if he enters number 3, then Python will take it as range(3). Let's just write the code in the loop body. Remember about four space indents.

That's what we've got:

countAuto = int(input("Enter the number of vehicles: ")) for i in range(countAuto): speed = int(input("Enter vehicle speed: ")) if (speed > 60 and speed <= 300): print("The driver violates the rules! Fine him, FINE!") elif (speed > 300): print("It isn't a plane. The entered speed is incorrect.") elif (speed == 0): print("The vehicle isn't moving. Like a stone. A stationary stone.") elif (speed < 0): print("The speed can't be negative. We are deeply sorry.") else: print("The driver doesn't violate the rules. The driver is good. Be like him.")

The result is:

Enter the number of vehicles: 3 Enter vehicle speed: 310 It isn't a plane. The entered speed is incorrect. Enter vehicle speed: 70 The driver violates the rules! Fine him, FINE! Enter vehicle speed: 35 The driver doesn't violate the rules. The driver is good. Be like him.

You can see that the previous code was executed as many times as the user had indicated in line "Enter the number of vehicles". We have got exactly what we planned! Who are good guys? We are good guys. Today we can afford tea with extra sugar.

# PRACTICE

## Exercise 1

Write a program that will output the first 20 exponents of the number 2 (from 0 till 19 inclusive). Remember that the sign of exponentiation in Python is **. For example, 2 ** 3 reflects the third exponent of the deuce (the result is 8).

Solution

for i in range(20): print("2 to the power of", i, "is", 2 ** i)

## Exercise 2

Write a program that will ask the user for a number and will output the reminder of division by two. Use a loop to ask and to output the result 10 times.

Solution

for i in range(10): x = int(input("Enter an integer: ")) print("The reminder of division the number by 2:", x % 2)

## Exercise 3

Write a program that will control the world the weather during a month (31 days). If the temperature is negative, then display "Cold" on the screen, if the temperature is zero, then display "Zero", if it is positive, then display "Warm". Notice that the temperature may not be lower than absolute zero (-173 -273 degrees Celsius. Thank you, Yura, for pointing out the mistake!), and above, for example, 50 degrees.

Solution

for i in range(31): x = int(input("Enter temperature: ")) if (x < -273 or x > 50): print("Error. The temperature is incorrect!") elif (x < 0): print("Cold") elif (x > 0): print("Warm") else: print("Zero")

Did you handle them? Let's go further!