Understanding For, While and other loops in python

The Purpose Of Loops

The purpose of loops is to repeat the same, or similar, code a number of times.  This number of times could be specified to a certain number, or the number of times could be dictated by a certain condition being met.  There are usually a number of different types of loops included in programming languages including for loops, while loops and do….while loops.

Definition: Loops are a programming element that repeat a portion of code a set number of times until the desired process is complete. Repetitive tasks are common in programming, and loops are essential to save time and minimize errors.

Printing A Number Sequence

Lets say that we want to print a sequence of numbers.  Lets say, 1 to 100 inclusive.  Now without loops we would have to do the following:

[codebox 1]

……. and so on.

Obviously not only is this time consuming, it is also very tedious.  Now, lets have a look what happens to the code if we use a loop, in this case, a for loop.

[codebox 2]

Now, as you can see, the code above is a lot more slick, easier to write and less time consuming.  The one possible disadvantage could be that its slightly harder to write and read (from a non-developers perspective).  However, even programmers with the most basic of experience should understand what you are doing with the for loop.

Two Ways To Implement Loops

So, the two ways you can use a loop are:

Repeating a block of statements with a specified and previously defined number of iterations to be completed.  In our example above, this is the way we have used looping – to print the numbers 1 to 100 inclusive.  We know to do this that we have to loop 100 times, there is no requirement for a condition to be attached to the loop.

Repeating a block of statements where the number of iterations is unknown and is based on other variables or conditions.

  1. Based on Number of iterations
  2. Based on certain Condition

Python while Loop Statements

while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true.

Syntax

The syntax of a while loop in Python programming language is −

while expression:
   statement(s)

Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately following the loop.

In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements.

Flow Diagram

while loop in Python

Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Example

#!/usr/bin/python

count = 0
while (count < 9):
   print 'The count is:', count
   count = count + 1

print "Good bye!"

When the above code is executed, it produces the following result −

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

The block here, consisting of the print and increment statements, is executed repeatedly until count is no longer less than 9. With each iteration, the current value of the index count is displayed and then increased by 1.

The Infinite Loop

A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.

An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as and when required.

#!/usr/bin/python

var = 1
while var == 1 :  # This constructs an infinite loop
   num = raw_input("Enter a number  :")
   print "You entered: ", num

print "Good bye!"

When the above code is executed, it produces the following result −

Enter a number  :20
You entered:  20
Enter a number  :29
You entered:  29
Enter a number  :3
You entered:  3
Enter a number between :Traceback (most recent call last):
   File "test.py", line 5, in <module>
      num = raw_input("Enter a number :")
KeyboardInterrupt

Above example goes in an infinite loop and you need to use CTRL+C to exit the program

Single statement while block

Just like the if block, if the while block consists of a single statement the we can declare the entire loop in a single line. If there are multiple statements in the block that makes up the loop body, they can be separated by semicolons (;).filter_none

edit

play_arrow

brightness_4

# Python program to illustrate  # Single statement while block  count = 0while (count < 5): count += 1; print("Hello Geek")

Output:

Hello Geek
Hello Geek
Hello Geek
Hello Geek
Hello Geek

Using else Statement with While Loop

Python supports to have an else statement associated with a loop statement.

  • If the else statement is used with a while loop, the else statement is executed when the condition becomes false.

The following example illustrates the combination of an else statement with a while statement that prints a number as long as it is less than 5, otherwise else statement gets executed.

#!/usr/bin/python

count = 0
while count < 5:
   print count, " is  less than 5"
   count = count + 1
else:
   print count, " is not less than 5"

When the above code is executed, it produces the following result −

0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

Python for Loop Statements

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 in Python programming
Flowchart of for Loop in Python

Example: Python for Loop

# Program to print all numbers stored in a list

# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

# iterate over the list
for val in numbers:
	print(val)
	

When you run the program, the output will be:

6
5
3
8
4
2
5
4
11

Doing it other way

# Program to print all numbers stored in a list


# iterate over the list
for val in [6, 5, 3, 8, 4, 2, 5, 4, 11]:
	print(val)


	

When you run the program, the output will be:

6
5
3
8
4
2
5
4
11

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 range(start, stop,step_size). step_size defaults to 1 if not provided.

The range object is “lazy” in a sense because it doesn’t generate every number that it “contains” when we create it. However, it is not an iterator since it supports inlen and __getitem__ operations.

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.

print(range(10))

print(list(range(10)))

print(list(range(2, 8)))

print(list(range(2, 20, 3)))

Output

range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17]

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 through a sequence using indexing. Here is an example.

# Program to iterate through a list using indexing

genre = ['pop', 'rock', 'jazz']

# iterate over the list using index
for i in range(len(genre)):
	print("I like", genre[i])

Output

I like pop
I like rock
​I like jazz

for loop with else

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.

The break keyword can be used to stop a for loop. In such cases, 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 = [0, 1, 5]

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.

This for...else statement can be used with the break keyword to run the else block only when the break keyword was not executed. Let’s take an example:

# program to display student's marks from record
student_name = 'Soyuj'

marks = {'James': 90, 'Jules': 55, 'Arthur': 77}

for student in marks:
    if student == student_name:
        print(marks[student])
        break
else:
    print('No entry with that name found.')

Output

No entry with that name found.

2 thoughts on “Understanding For, While and other loops in python

  • Pingback: break and continue Statements in python - cbseshala

  • Pingback: multiplication table of N - cbseshala

Leave a Reply

Your email address will not be published. Required fields are marked *