Iteration in Python
Iterations are performed through ‘for’ and ‘while’ loops. Iterations execute a set of
instructions repeatedly until some limiting criteria is met. In contrast to recursion,
iteration does not require temporary memory to keep on the results of each iteration.
Rather, programmers should define a variable (a number, or list, or string, or any mutable
data type) well before the start of iterative calls to collect the results (if there are such
arithmetic results) during each iteration.
Further, an iterative task can be accomplished by either a ‘for’ loop or a ‘while’ loop. A ‘for’
loop iterates over a sequence (such as a list, string, tuple and range). It terminates the loop
when there is no element left in the sequence. It automatically traverses through the
successive elements. But a ‘while’ loop needs initialization of an iterator and manual
incrementation of the same. A ‘while’ loop is executed until an iterator-based condition is
satisfied.
Factorial of an Integer
Calculating factorial is a popular use case to understand iteration and recursion. For
instance, we wish to calculate the factorial of 10. It can be determined as
1*2*3*4*5*6*7*8*9*10 = 3628800. This can be viewed as 10 subproblems of multiplying
an incrementing integer to a final result.
# using a for loop
n = 10
result = 1
for i in range(1,n+1):
result *= i
print(result)
Output:
A range function is implemented in a ‘for’ loop since it requires a sequence to iterate over.
Range function supplies values iteratively from 1 through 10, one at a time. It stops
iteration when the range function stops supplying values(i.e., at 10).
# using a while loop
n = 10
result = 1
i=1
while i <= n:
result *= i
i += 1
print(result)
Output:
In a ‘while’ loop, an iterator i is introduced and incremented through every loop. While loop
stops iterating when the value of i exceeds the integer 10.
# using recursion
def Factorial(n):
# declare a base case (a limiting criteria)
if n == 1:
return 1
# continue with general case
else:
return n * Factorial(n-1)
print(Factorial(10))
Output:
A recursive function, named Factorial(), is defined with the limiting criteria of n=1. It first
attempts to find the factorial of 10. Factorial(10) is broken down into 10 * Factorial(9).
Further, Factorial(9) is broken down into 9 * Factorial(8), and so on. When Factorial(1) is
called, it stops the recursion.
A few steps in the recursive version of Factorial problem.
Factorial(10) awaits for the value of Factorial(9). Factorial(9) awaits for the value of
Factorial(8), and so on. Thus once the limiting criteria (here, n=1) is reached, it starts
returning the values.
Reverse a String
A string or a sequence can be reversed through iteration or recursion. Here, we define a
function that takes a string and returns its reversed form through an iterative approach.
This function can be called any number of times with different strings each time.
def Reverse_iter(s):
rev = ''
for k in s:
rev = k + rev
return rev
Reverse_iter('Welcome!')
Output:
The same task is performed through a recursive approach as follows.
def Reverse_rec(s):
if not s:
return ''
else:
return Reverse_rec(s[1:]) + s[0]
Reverse_rec('Welcome!')
Output:
Build a Triangle with Numbers
Build a triangle of numbers by printing 1 on the first line, 1 thousand on the second line, 1
million on the third line and so on, until a prescribed number of lines. After constructing
the lengthy line, decrease the number of digits in descending order. The total number of
lines printed would be equal to 2n+1, where n is the input number.
# Iterative form
n=8
# rise up
for i in range(n):
print(10**(3*i))
# fall down
for i in range(n, -1, -1):
print(10**(3*i))
Output:
In the above construction, the first loop printed the ascending sequence, and the second
loop printed the descending sequence. The same can be implemented with a recursive
function as follows.
# recursive form
def Triangle(n, i=0):
if n==0:
print(1)
return None
print(10**(3*i))
if i<n:
# raise up
Triangle(n, i+1)
else:
# fall down
Triangle(n-1, i-1)
Triangle(8)
Output:
Though the same results are obtained through both iterative and recursive approaches, the
recursive approach takes a tough path while the iterative approach follows a
straightforward path. This is the kind of problem in which the recursive approach is highly
discouraged. However, understanding recursion with this kind of simple problem may help
one understand advanced algorithms that rely heavily on recursions, such
as backtracking and dynamic programming.
2.
Basis of
For Loop While Loop
Comparison
for object in sequence: while condition:
Declaration
<indentation>body <indentation>body
Initialization, condition checking, and
Only initialization and condition checking
Format iteration statements are written at the
is written at the top
top
When you already know the number When you don’t know the number of
Use Case
of iterations iteration.
Every element is fetched through the Every element is explicitly incremented or
Iteration
iterator/generator. Example, range() decremented by the user
For loop can be iterated on generators While loop cannot be iterated on
Generator Support
in Python. Generators directly.
For loop with range() uses 3 While loop with incrementing variable
Disassembly operations. range() function is uses 10 operations. i+=1 is interpreted,
implemented in C, so, its faster. hence, it’s slower than range()
Speed (May Vary On basis of disassembly, for loop is On basis of disassembly, the while loop is
on Conditions) faster than while loop. slower than for loop.
3.
Invalid Syntax in Python: Common Reasons for SyntaxError
1. Misusing the Assignment Operator (=)
2. Misspelling, Missing, or Misusing Python Keywords.
3. Missing Parentheses, Brackets, and Quotes.
4. Mistaking Dictionary Syntax.
5. Using the Wrong Indentation.
6. Defining and Calling Functions.
7. Changing Python Versions.