Python Loop Program

In this article, we will understand the various types of loops in Python. Loops are considered in the control flow statements, as we can control them according to our requirements.

In computer programming, loops are used to run a section of code repeatedly. You can, for example, use a loop to display the same message 100 times instead of entering the same code 100 times.

Two different loop types exist in Python.:

  • while loop
  • for loop

While Loop in Python

In Python, a while loop is used to continuously execute a set of instructions up until a certain condition is satisfied. And when the condition switches to false, the line in the program that comes after the loop is executed.

While Loop Syntax:

while expression:
    statement(s)

A block of code is defined as all the statements that follow a programming construct with the same number of character spaces indented. Python groups statements together with indentation.

Python While Loop Program

count = 0
while (count < 3):
    count = count + 1
    print("Hello PrepBuddy")

Output

Hello PrepBuddy
Hello PrepBuddy
Hello PrepBuddy

Using else statement with while loops

As previously said, a while loop runs the block till the condition is satisfied. The statement that comes right after the loop is performed when the condition turns false.

Only when your while condition becomes false else clause come into play. It won’t be run if you exit the loop or if an exception is thrown.

If else like this:

if condition:
    # execute these statements
else:
    # execute these statements
and while loop like this are similar

while condition:
     # execute these statements
else:
     # execute these statements

Python Program of IfElse with While loop

count = 0
while (count < 3):
    count = count + 1
    print("Hello PrepBytes")
else:
    print("In Else Block")

Output

Hello PrepBytes
Hello PrepBytes
Hello PrepBytes
In Else Block

Single statement while block

The complete loop can be declared on a single line, as seen below, if the while block only has one statement, similar to how the if block only contains one statement:

count = 0
while (count == 0): print("Hello PrepBuddy")

Note: It is advised against using this kind of loop since it creates a forcefully terminating infinite loop where the condition is always true.

For Loop in Python

For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is no C style for loop, i.e., for (i=0; i< n; i++). There is “for in” loop which is similar to for each loop in other languages. Let us learn how to use for in loop for sequential traversals.

For Loop Syntax:

for iterator_var in sequence:
    statements(s)

It can be used to iterate over a range and iterators.

For Loop Python Program

n = 5
for i in range(0, n):
    print(i, end=" ")

Output

0 1 2 3 4

Here is the for loop example with List, Tuple, string, and dictionary iteration using For Loops

print("List Iteration")
l = ["For", "Learning", "Coding,", "join", "PrepBytes"]
for i in l:
    print(i, end=" ")


print("\nTuple Iteration")
t = ("For", "Learning", "Coding,", "join", "PrepBytes")
for i in t:
    print(i, end=" ")

print("\nString Iteration")
s = "For Learning Coding Join PrepBytes"
for i in s:
    print(i, end ="")

print("\nDictionary Iteration")
d = dict()
d['Prep'] = 123
d['Bytes'] = 345
for i in d:
    print("%s %d" % (i, d[i]))

print("\nSet Iteration")
set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
    print(i, end = " ")

Output

List Iteration
For Learning Coding, join PrepBytes 
Tuple Iteration
For Learning Coding, join PrepBytes 
String Iteration
For Learning Coding Join PrepBytes
Dictionary Iteration
Prep 123
Bytes 345

Set Iteration
1 2 3 4 5 6 

Using else statement with for loops:
We can also combine the else statement with for loop like in while loop. But as there is no condition in for loop based on which the execution will terminate so the else block will be executed immediately after for block finishes execution.
Below example explains how to do this:

list = ["For", "Learning", "Coding", "Join", "PrepBytes"]
for index in range(len(list)):
    print (list[index])
else:
    print ("Inside Else Block")

Output

For
Learning
Coding
Join
PrepBytes
Inside Else Block

Other Python Programs
Python program to reverse a number
Python program for heap sort
Python program to check armstrong number
Python program to check leap year
Python program to convert celsius to fahrenheit
Python program to find factorial of a number
Python program to reverse a linked list
Python Program to find the middle of a linked list using only one traversal
Python Program to Add Two Numbers
Python Program to Check Palindrome Number
Python Program to Print the Fibonacci Series

Leave a Reply

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