July 2019

For loop in Python Programming

What is for loop in Python Programming?

The for loop in Python Programming is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.


Syntax of for Loop

for val in sequence:
        Body of for
Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.


Flowchart of for Loop

Flowchart of for Loop

Example: Python for Loop
# Program to find the sum of all numbers stored in a list

# List of numbers
numbers = [6538425411]

# variable to store the sum
sum = 0

# iterate over the list
for val in numbers:
    sum = sum+val

# Output: The sum is 48
print("The sum is"sum)

when you run the program, the output will be:
The sum is 48


The range() function

We can generate a sequence of numbers using range() function. range(10) will generate numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size as a range(start, stop, step size). step size defaults to 1 if not provided.
This function does not store all the values in memory, it would be inefficient. So it remembers the start, stop, step size and generates the next number on the go.
To force this function to output all the items, we can use the function list().
The following example will clarify this.
# Output: range(0, 10)
print(range(10))
# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(10)))
# Output: [2, 3, 4, 5, 6, 7]
print(list(range(2, 8)))
# Output: [2, 5, 8, 11, 14, 17]
print(list(range(2, 20, 3)))   
We can use the range() function in for loops to iterate through a sequence of numbers. It can be combined with the len() function to iterate though a sequence using indexing. Here is an example.

When you run the program, the output will be:
I like Classical
I like rock
I like Bollywood


for loop with else
A for loop can have an optional else block as well. The else part is executed if the items in the sequence used in for loop exhausts.
break statement can be used to stop a for loop. In such case, the else part is ignored.
Hence, a for loop's else part runs if no break occurs.
Here is an example to illustrate this.
digits = [015]
for i in digits:
    print(i)
else:
    print("No items left.")
When you run the program, the output will be:
0
1

5

No items left.
Here, the for loop prints items of the list until the loop exhausts. When the for loop exhausts, it executes the block of code in the else and prints
No items left.


While Loop in Python Programming

What is while loop in Python?

The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.
We generally use this loop when we don't know beforehand, the number of times to iterate.
Syntax of while Loop in Python
while test_expression:
    Body of while
In while loop, test expression is checked first. The body of the loop is entered only if the test_expression evaluates to True. After one iteration, the test expression is checked again. This process continues until the test_expression evaluates to False.
In Python, the body of the while loop is determined through indentation.
Body starts with indentation and the first unindented line marks the end.
Python interprets any non-zero value as TrueNone and 0 are interpreted as False.


Flowchart of while Loop
Flowchart of while Loop


What is the use of break and continue in Python?
In Python, break and continue statements can alter the flow of a normal loop.
Loops iterate over a block of code until the test expression is false, but sometimes we wish to terminate the current iteration or even the whole loop without checking test expression.

The break and continue statements are used in these cases.


Python break statement
The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop.
If the break statement is inside a nested loop (loop inside another loop), the break will terminate the innermost loop.
The break statement in Python terminates the current loop and resumes execution at the next statement, just like the traditional break found in C.
The most common use for a break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops.
Syntax of break
break
Flowchart of break

Example: Python break
# Use of break statement inside loop
for val in "string":
    if val == "i":
        break
    print(val)
print("The end")

Output
s
t
r
The end



Python continue statement
The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration.
The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.
The continue statement can be used in both while and for loops.

Example:

var = 10                 

while var > 0:             
   var = var -1
   if var == 5:
      continue
   print 'Current variable value :', var
print "Good bye!"
This will produce following result:
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Good bye!


Syntax of Continue
continue
Flowchart of continue 






Pass Statement in Python

The pass statement is a null operation; nothing happens when it executes.  The difference between a comment and pass statement in Python is that, while the interpreter ignores a comment entirely, the pass is not ignored. It is used when a statement is required syntactically but you do not want any command or code to execute.
The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example) −
Syntax
pass

Example

for a letter in 'Python':
   if letter == 'h':
      pass
      print 'This is pass block'
   print 'Current Letter :', letter

print "Goodbye!"
When the above code is executed, it produces the following result −
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. They cannot have an empty body. The interpreter would complain. So, we use the pass statement to construct a body that does nothing.
Example: pass Statement
# pass is just a placeholder for
# functionality to be added later.
sequence = {'p''a''s''s'}
for val in sequence:
    pass

We can do the same thing in an empty function or class as well.
1.   
2.  def function(args):
3.      pass
1.   
2.  class example:
3.      pass