facebook twitter pinterest google plus Youtube
www.TestsTestsTests.com

Computer Programming Languages - Python
Free Online Python For Loops Tutorial

* Range() Function
* For Loop Structure and Syntax
* Loop Body
* Loop Through Strings
* Nested Loops

Python is a modern general-purpose programming language, equally popular among beginner programmers and professionals. Its’ clear and consistent syntax is a great way to start the exciting journey into computing. At the same time, it provides quite a comprehensive set of tools to enable development of sophisticated projects.

Test your Python Computer Programming skills with the corresponding
FREE Online Python For Loops Test


Python Computer Programming Tutorial - Python for Loop


Python’s creator, Guido van Rossum, chose a short, unique, and slightly mysterious name after a BBC comedy series from the 1970s.

Free Python IDLE environment, downloadable from the official website, provides a working area with a basic graphical user interface. An interactive interpreter enables writing and executing code line by line, which makes the programming process straightforward and easy to start.

Python Computer Programming Tutorial - Python for Loop


Every programming code implements an algorithm, solving given problem and achieving some result.
For example, let’s look at an algorithm calculating the balance of a bank account with a known rate over 10 years. The solution to this problem involves ten repeated calculations of the yearly balance.

Problem

Algorithm

Python code *

Calculate the balance of a bank account with a known rate over 10 years.
python-tutorial-python-for-loops

1) Provide the values of the starting balance and account rate.
2) Calculate the new balance for the end of the year by adding the yearly income (balance multiplied by rate) to the balance at the start of the year.
3) Repeat step 2 ten times.
4) Announce the final balance.

balance = 1000
rate = 0.05
for year in range(10):
         balance += balance*rate
print (balance)

 

Result:
1628.894626777441


A detailed explanation of the Python code follows below


Python Computer Programming Tutorial - Python for Loop

The statement starting with for in this code represents the loop concept which allows executing the same line(s) of code multiple times. There are two basic types of loops:

- Definite loops are used when we know the number of iterations at the beginning of a loop.
- Conditional loops are used when the number of repetitions depends on some condition, subject to a change inside this loop.

A loop in algorithms always follows a similar structure:
Step 1. Define and initiate variables.
Step 2. Set the number of repetitions for a definite loop or formulate a condition for a conditional loop.
Step 3. Perform some commands inside the loop body.

Proper usage of loops makes programming code concise and effective.

* Range() Function

Python can iterate through different bunches of items: numbers, letters, strings, list items etc. The range() function creates a set of numbers as arithmetic progression. This function can take three parameters:

  • the starting number, included in the resulting set of values;
  • the finishing number, excluded from the resulting set of values;
  • the value of an increment, also called step. This value may be positive or negative. The increment means that the next number of a progression is different from the previous one by the value of step.

It’s possible to set only one or two parameters, so the omitted ones would take the default values. The starting number defaults to 0, and increment is equal to 1. There’s no default value for a finishing number, so this is the only required parameter of the range() function.

For example, in the function call range(1,10,3), the starting number is 1 (included), the finishing number is 10 (excluded), the step is 3, which makes the set of the numbers [1,4,7] the result of this function.

Python Computer Programming Tutorial - Python For Loop Range Function 
The function range(3,-3,-2) would create the set of numbers [3,1,-1] as it starts with 3 and goes down to -3 (excluding this number) with a step of -2. If we needed a list of [3,1,-1,-3], the function would have to be written as range(3,-4,-2) to accommodate the inclusion of -3.

Python Computer Programming Tutorial - Python For Loop Range Function

* For Loop Structure and Syntax

A definite loop is used to program repetition of some code for a specified number of times. Some kind of a sequence (of numbers, letters or other items) should be defined and iterated in a for-statement.

The coding template of a definite loop in Python looks as follows:
    for counter in sequence :
         loop body

Counter
is a variable that is being changed with each execution (also called iteration) of a loop. The loop body consists of command(s) that are supposed to be executed repeatedly.

It’s important to follow the Python syntax, that demands a colon at the end of the for statement, and indentation for the loop body.

Sequence for looping through may take a form of a list of numbers (created with a range() function), a string of characters or an array of items.

for
number
sequence of numbers generated by range () function
0 1 2 3 4 5 6
for
letter
string of characters
j u k e b o x
for
item
list of items
Sunday Monday Tuesday Wednesday Thursday Friday Saturday


The execution of a loop takes the following steps:

Step 1. Define a sequence of items.
Step 2. Execute the loop body statements.
Step 3. If there are unused items in a sequence, go back to step 2, else continue to process further statements outside the loop body.


Python Computer Programming Tutorial - Python For Loop Structure and Synatax



* Loop Body

Loop body may contain different statements, but the most usual are printing operations as well as calculations of different kind.

Let’s take a look at the following Python example of a loop body containing a print() function:
for number in range(10):
      print (number)
The result of the execution of this code fragment is the following:
0
1
2
3
4
5
6
7
8
9

The range() function produced a progression of numbers [0,1,2,3,4,5,6,7,8,9]. The print() function prints all of its’ arguments and jumps into the next line. So the variable number is iterated through the defined progression, and each of its values is printed out in a new line.

In order to make it all into a single line, it’s possible to add some parameters to the print() function:

  • end=”string“ means that a string is added to the end of each print-statement result. By default it’s “\n”, which stands for a new line.
  • sub=”string” means that a string is inserted between the printed arguments. By default it’s a single space.

So, changing the loop body into:
    print(number, end=" ")
we'd get the following result:
0 1 2 3 4 5 6 7 8 9

Quite often it’s necessary to make some calculations inside the loop. In this case an accumulator is needed – a variable to store the value, subjected to a change in the loop body. It’s important to initialize this variable with some value before the loop, otherwise the Python would throw a NameError: name is not defined.

Changing the value of the variable involves performing calculations and storing the new value in the same variable. Python provides the following syntax for such operations:

var = var + 1

var += 1

total = total + number

total += number

result = result * 5

result *= 5

change = change / 25

change /= 25

remainder = remainder % 2

remainder  %= 2

power = power ** 3

power ** = 3


The statements in both columns are equivalent
and a Python developer may use the syntax of any shown type, but often it’s more convenient and quick to utilize the shortened notation.

We can now analyze the example from the beginning of this tutorial:
balance = 1000
rate = 0.05
for year in range(10):
         balance += balance*rate
print (balance)

The variable balance is an accumulator, initialized before the loop.
In the loop we iterate through the counter year, which takes the values 0,1,2,3,4,5,6,7,8,9. The loop body consists of a calculation by determining the yearly income (that is balance multiplied by rate), and adding it to the balance, updating its value. At the end of the loop we print out the final balance.
You can follow the execution of the loop and visualization of the variables’ changes on this website or in the following table.

year

balance

0

1050.0

1

1102.5

2

1157.625

3

1215.50625

4

1276.2815624999998

5

1340.0956406249998

6

1407.1004226562497

7

1477.4554437890622

8

1551.3282159785153

9

1628.894626777441


* Loop Through Strings

A loop can iterate through sequential items of different types, including characters of a string.
for letter in "Python":
    print(letter)

The sequence in this loop is a set of characters forming the word “string”. The counter variable is called letter and it takes the values of individual letters [‘P’,’y’,’t’,’h’,’o’,’n’]. The loop body contains a print() statement, that produces the following result:
P
y
t
h
o
n

While working with strings, it’s nice to know that it’s possible to add and multiply them by numbers in Python. For example, the code:

for letter in "Python":
    print(letter*2, end="")
produces the following result:
PPyytthhoonn

This means that each of the letters were doubled, and the print() function did not jump to the new line after printing those doubled letters.

* Nested Loops

A loop can be placed inside another loop. In this case each iteration of an outer loop would involve full iteration of the inner loop.

For example, if we need to find different weather combinations of the sky and temperature conditionss, it’s possible to write the following  code:

for sky in ["clear","cloudy","overcast"]:
    for temperature in ["hot","cold"]:
        print("The sky is", sky, "and it is", temperature, "today")

The result is as follows:
The sky is clear and it is hot today
The sky is clear and it is cold today
The sky is cloudy and it is hot today
The sky is cloudy and it is cold today
The sky is overcast and it is hot today
The sky is overcast and it is cold today

Python Computer Programming Tutorial - Python For Loop Nested Loop

The outer loop iterates variable sky through the values of ["clear","cloudy","overcast"] and the inner loop iterates through the values of ["hot","cold"] for temperature. So for each of the three sky conditions, we get two temperature values.

sky

temperature

clear

hot

cold

cloudy

hot

cold

overcast

hot

cold

Notice the usage of lists as sequences for the loops in this example, where we explicitly enumerate items to use as a counter values.

Test your Python Computer Programming skills with the corresponding
FREE Online Python For Loops Test