Python Loops (for, while, and nested loops)

This article entitle Python Loops is a continuation of the previous article entitled Python Decision Making.

Python Loops provides types of loops to handle the looping requirements and also provides three different ways for executing each loop. While the other ways provide only a similar basic functionality that is different from their syntax and condition time checking.

What are Python Loops?

  • For loop
  • While loop
  • Nested loop

Python for loop

A for loop is mainly used for iterating above a sequence which can be a tuple, list, set, dictionary, or string. This is similar to a keyword in some programming languages and works similarly to the iterator method that can be found in other object-orientated programming languages.

Syntax

for iterator_var in sequence:
    statements(s)

Example

# Python program to illustrate
# Iterating over range 0 to n-1

x = 5
for i in range(0, x):
	print(i)

Output

0
1
2
3
4

For loop example with a Tuple, List, string, and dictionary

# Python program to illustrate
# Iterating over a list
print("List Iteration")
l = ["sourcecodehero", "for true", "heroes"]
for i in l:
	print(i)

# Iterating over a tuple (immutable)
print("\nTuple Iteration")
t = ("sourcecodehero", "for true", "heroes")
for i in t:
	print(i)

# Iterating over a String
print("\nString Iteration")
s = "SOURCECODEHERO"
for i in s:
	print(i)

# Iterating over dictionary
print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d:
	print("%s %d" % (i, d[i]))

# Iterating over a set
print("\nSet Iteration")
set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
	print(i),

Output

List Iteration
sourcecodehero
for true
heroes

Tuple Iteration
sourcecodehero
for true
heroes

String Iteration
S
O
U
R
C
E
C
O
D
E
H
E
R
O

Dictionary Iteration
xyz 123
abc 345

Set Iteration
1
2
3
4
5
6

Iterating an index of sequences using for loop

There is also another way to iterate a sequence with the use of index elements. The main idea is to calculate first the length of a list and iterate it over on the sequence within the range of the length.

Example

# Python program to illustrate
# Iterating by index

list = ["SOURCECODEHERO", "for true", "HEROES"]
for index in range(len(list)):
	print list[index]

Output

SOURCECODEHERO
for true
HEROES

Python While Loop

A while loop is used for executing a block of statements repeatedly until the given condition is met. Also, the conditions become false, after the loop the line is immediately executed.

All the indented statements with the same number of character spaces after a program construct is considered to be a part of one block of code.

Syntax

while expression:
    statement(s)

Example

# Python program to illustrate
# while loop
count = 0
while (count < 3):
	count = count + 1
	print("Hello true Heroes")

Output

Hello true Heroes
Hello true Heroes
Hello true Heroes

While loop with else statement

The else clause can only be executed once the while conditions become false. If you want to break out the loop or the exceptions have been raised the result will not be executed

Syntax

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

Example

# Python program to illustrate
# combining else with while
count = 0
while (count < 3):
	count = count + 1
	print("Hello true Heroes")
else:
	print("In Else Block")

Output

Hello true Heroes
Hello true Heroes
Hello true Heroes
In Else Block

Python Nested loop

In Python, a nested loop is a loop that was inside the body of the outer loop, and the inner or outer loop consists of any type of loop such as for or a while loop.

Syntax of nested for loop statement

for iterator_var in sequence:
   for iterator_var in sequence:
       statements(s)
       statements(s)

Syntax of nested while loop statement

while expression:
   while expression: 
       statement(s)
       statement(s)

A nested loop is a built-in function type of loop in which we can put any type of loop inside of any type of loop such as for loop or while loop or vice versa.

Example

# Python program to illustrate
# nested for loops in Python

from __future__ import print_function
for i in range(1, 9):
	for j in range(i):
		print(i, end=' ')
	print()

Output

1 
2 2 
3 3 3 
4 4 4 4 
5 5 5 5 5 
6 6 6 6 6 6 
7 7 7 7 7 7 7 
8 8 8 8 8 8 8 8 

Python Loop Control Statements

A loop control statement is an execution that will be changed from its normal sequence execution. Once the execution will leave a scope all the objects that are automatic and have been created on that scope will be destroyed.

Break Statement – It will bring out the control of the loop

Example

for letter in 'sourcecodehero':

	# break prints the loop as soon it sees 'o'
	# or 'd'
	if letter == 'o' or letter == 'd':
		break

print ('Current Letter :', letter)

Output

Current Letter : o

Continue Statement – It will return the beginning of control of the loop

# Continue prints all letters except 'd' and 'e'

for letter in 'sourcecodehero':
	if letter == 'd' or letter == 'e':
		continue
	print ('Current Letter :', letter)
	var = 5

Output

Current Letter : s
Current Letter : o
Current Letter : u
Current Letter : r
Current Letter : c
Current Letter : c
Current Letter : o
Current Letter : h
Current Letter : r
Current Letter : o

Pass Statement – This statement is used to write an empty loop and is also used for empty control statements, classes, and functions.

Example

# An empty loop

for letter in 'sourcecodehero':
	pass
print ('Last Letter :', letter)

Output

Last Letter : o

Summary

In summary, you have read about Python Loops. We also discussed in this article what is decision-making, single statement suites, and types of decision-making statements.

I hope this article about Loops in Python programming language could help you a lot to continue pursuing learning this powerful programming language.

If you want to learn more check out my previous and latest articles for more career-changing articles.

Leave a Comment