Menu Close

For and While loops

Programmers often need to perform specific operations multiple times. For this, there are two types of loops for performing an operation multiple times. They are the for and while loops. The for loop performs an operation a specific, pre-determined number of times, while the while loop performs an operation until a condition is met.

For loops:

A for loop will loop through a given block of code a certain number of times. The most common syntax for a simple for loop is as follows:

for i in range(n):
     #code

What this represents is for each object in a range object of length n. The n can represent any integer. The range(n) object is a tuple of consecutive values from 0 to n – 1. The for loop therefore represents each number as i, which can be used within the code.

One way to use i is for accessing objects in a list.

Example 1:

myList = [“Canada”, “United States”, “Japan”, “Germany”, “United Kingdom”]

for i in range(len(myList)):
     print(myList)

Output:

Canada
United States
Japan
Germany
United Kingdom

As i increases by one every time, we can use it to access every value within a list or tuple.

Example 2:

The following example is used to calculate the terms within the Fibonacci Sequence

value1 = 0
value2 = 1

term = 10
for i in range(term - 2):
     temp = value2
     value2 += value1
     value1 = temp
print(value2)

Output:

34

The code works by setting a temporary variable to store the value of value2, then adding value1 to value2. At the end, it sets value1 to the temporary value to represent the previous term. The loop does term – 2 times as the first and second term are already represented in the forms of value1 and value2.

Enhanced For Loop:

The enhanced for loop will go through every value in an iterable and modify or access these values directly. Rather than using iterable[index], the values are represented directly using a predefined variable.

This is the syntax for an enhanced for loop:

for variable in iterable:
     #code

This looks very similar to the syntax of the regular for loop. This is because the range() object itself is an iterable, and we are iterating through the consecutive integer values within it.

There are many ways to use enhanced for loops with iterables.

Example 1:

countryList = [“Canada”, “United States”, “Japan”, “Germany”, “United Kingdom”]

for country in countryList:
     print(country)

Output:

Canada
United States
Japan
Germany
United Kingdom

Example 2:

newName = “John Gary Smith”
charList = []

for letter in newName:
     charList.append(letter)

print(charList)

Output:

['J', 'o', 'h', 'n', ' ', 'G', 'a', 'r', 'y', ' ', 'S', 'm', 'i', 't', 'h']

While loops:

A while loop will continuously execute a block of code as long as a condition is true.

The syntax for the while loop is as follows:

while condition:
     #code

As while loops have no set number of times they can loop for, they are very useful when it is unknown how many iterations will occur.

Example 1:

The following code will check how many terms are needed to reach at least a certain value.

value1 = 0
value2 = 1

term = 2
toReach = 100

while value2 < toReach:
     temp = value2
     value2 += value1
     value1 = temp
     term += 1

print(term)

Output:

13

In the code above, the while loop continuously checks whether value2 is less than toReach. The variable toReach represents the threshold that needs to be passed. The code will continually loop until value2 surpasses toReach.

Example 2:

countryList = [“Canada”, “United States”, “Japan”, “Germany”, “United Kingdom”]

while len(countryList) != 0:
     print(countryList[0])
     del countryList[0]

Output:

Canada
United States
Japan
Germany
United Kingdom

The reason why a while loop is advantageous in this case is because the list countryList could be any length and the code will still work.

Infinite loops

Because while loops will continuously run as long as a condition is true, we can replace the expression with the keyword True to create an infinite loop.

Example:

x = 0
while True:
     x += 5
     print(x)

Output:

5
10
15
20
25
30
35
40
…

This code will infinitely generate multiples of 5 until the process has been forcefully terminated.

Posted in Embedded Programming Language, Python

Related Articles

Leave a Reply

Your email address will not be published.

Leave the field below empty!