Loops in Python – For, While and Nested Loops
Loops in Python are used to repeat actions efficiently. The main types are For loops (counting through items) and While loops (based on conditions). Additionally, Nested Loops allow looping within loops for more complex tasks. While all the ways provide similar basic functionality, they differ in their syntax and condition-checking time. In this article, we will look at Python loops and understand their working with the help of examples.
While Loop in Python
In Python, a while loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed.
Python While Loop Syntax:
while expression:
statement(s)
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.
Example of Python While Loop:
cnt = 0
while (cnt < 3):
cnt = cnt + 1
print("Hello Geek")
Output
Hello Geek Hello Geek Hello Geek
Using else statement with While Loop in Python
Else clause is only executed when our while condition becomes false. If we break out of the loop or if an exception is raised then it won’t be executed.
Syntax of While Loop with else statement:
while condition:
# execute these statements
else:
# execute these statements
Example:
The code prints “Hello Geek” three times using a ‘while’ loop and then after the loop it prints “In Else Block” because there is an “else” block associated with the ‘while’ loop.
cnt = 0
while (cnt < 3):
cnt = cnt + 1
print("Hello Geek")
else:
print("In Else Block")
Output
Hello Geek Hello Geek Hello Geek In Else Block
Infinite While Loop in Python
If we want a block of code to execute infinite number of times then we can use the while loop in Python to do so.
The code given below uses a ‘while’ loop with the condition (count == 0) and this loop will only run as long as count is equal to 0. Since count is initially set to 0, the loop will execute indefinitely because the condition is always true.
count = 0
while (count == 0):
print("Hello Geek")
Note: It is suggested not to use this type of loop as it is a never-ending infinite loop where the condition is always true and we have to forcefully terminate the compiler.
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 “for in” loop which is similar to foreach loop in other languages. Let us learn how to use for loops in Python for sequential traversals with examples.
For Loop Syntax:
for iterator_var in sequence:
statements(s)
n = 4
for i in range(0, n):
print(i)
Output
0 1 2 3
Explanation: This code prints the numbers from 0 to 3 (inclusive) using a for loop that iterates over a range from 0 to n-1 (where n = 4).
Example with List, Tuple, String, and Dictionary Iteration Using for Loops in Python
We can use for loop to iterate lists, tuples, strings and dictionaries in Python.
li = ["geeks", "for", "geeks"]
for i in li:
print(i)
tup = ("geeks", "for", "geeks")
for i in tup:
print(i)
s = "Geeks"
for i in s:
print(i)
d = dict({'x':123, 'y':354})
for i in d:
print("%s %d" % (i, d[i]))
set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
print(i),
Output
geeks for geeks geeks for geeks G e e k s x 123 y 354 1 2 3 4 5 6
Iterating by the Index of Sequences
We can also use the index of elements in the sequence to iterate. The key idea is to first calculate the length of the list and in iterate over the sequence within the range of this length.
list = ["geeks", "for", "geeks"]
for index in range(len(list)):
print(list[index])
Output
geeks for geeks
Explanation: This code iterates through each element of the list using its index and prints each element one by one. The range(len(list)) generates indices from 0 to the length of the list minus 1.
Using else Statement with for Loop in Python
We can also combine 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.
list = ["geeks", "for", "geeks"]
for index in range(len(list)):
print(list[index])
else:
print("Inside Else Block")
Output
geeks for geeks Inside Else Block
Explanation: The code iterates through the list and prints each element. After the loop ends it prints “Inside Else Block” as the else block executes when the loop completes without a break.
Nested Loops in Python
Python programming language allows to use one loop inside another loop which is called nested loop. Following section shows few examples to illustrate the concept.
Nested Loops Syntax:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in the Python programming language is as follows:
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that we can put any type of loop inside of any other type of loops in Python. For example, a for loop can be inside a while loop or vice versa.
from __future__ import print_function
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()
Output
1 2 2 3 3 3 4 4 4 4
Explanation: In the above code we use nested loops to print the value of i multiple times in each row, where the number of times it prints i increases with each iteration of the outer loop. The print() function prints the value of i and moves to the next line after each row.
Loop Control Statements
Loop control statements change execution from their normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements.
Continue Statement
The continue statement in Python returns the control to the beginning of the loop.
for letter in 'geeksforgeeks':
if letter == 'e' or letter == 's':
continue
print('Current Letter :', letter)
Output
Current Letter : g Current Letter : k Current Letter : f Current Letter : o Current Letter : r Current Letter : g Current Letter : k
Explanation: The continue statement is used to skip the current iteration of a loop and move to the next iteration. It is useful when we want to bypass certain conditions without terminating the loop.
Break Statement
The break statement in Python brings control out of the loop.
for letter in 'geeksforgeeks':
if letter == 'e' or letter == 's':
break
print('Current Letter :', letter)
Output
Current Letter : e
Explanation: break statement is used to exit the loop prematurely when a specified condition is met. In this example, the loop breaks when the letter is either ‘e’ or ‘s’, stopping further iteration.
Pass Statement
We use pass statement in Python to write empty loops. Pass is also used for empty control statements, functions and classes.
for letter in 'geeksforgeeks':
pass
print('Last Letter :', letter)
Output
Last Letter : s
Explanation: In this example, the loop iterates over each letter in ‘geeksforgeeks’ but doesn’t perform any operation, and after the loop finishes, the last letter (‘s’) is printed.
How for loop works internally in Python?
Before proceeding to this section, we should have a prior understanding of Python Iterators.
Firstly, lets see how a simple for loops in Python looks like.
Example: This Python code iterates through a list called fruits, containing “apple”, “orange” and “kiwi.” It prints each fruit name on a separate line, displaying them in the order they appear in the list.
fruits = ["apple", "orange", "kiwi"]
for fruit in fruits:
print(fruit)
This code iterates over each item in the fruits list and prints the item (fruit) on each iteration and the output will display each fruit on a new line.
This Python code manually iterates through a list of fruits using an iterator. It prints each fruit’s name one by one and stops when there are no more items in the list.
fruits = ["apple", "orange", "kiwi"]
iter_obj = iter(fruits)
while True:
try:
fruit = next(iter_obj)
print(fruit)
except StopIteration:
break
Output
apple orange kiwi
We can see that under the hood we are calling iter() and next() method.
Quiz:
Related Posts:
- Python While Loop
- Python For Loops
- Python Do While Loops
- Python Nested Loops
- Loop Control Statements
- Difference between for loop and while loop in Python
- Looping Techniques in Python
- Use for Loop That Loops Over a Sequence in Python
- Eliminating Loop from Python Code
- Iterate over a list in Python
- Python loop-programs Archives
Recommended Problems:
- For loop – Python
- For Loop – 1
- For Loop 2- Python
- While Loop
- While loop in Python
- Jumping through While
- Zero Converter
- Multiplication Table
- Sum of Natural Numbers
- Table Difference
- Print Square wall
- Print Square Wall Using Nested Loops
- Right Angle Triangle
- Right Angle Triangle 2
- Inverted Right Angle Triangle
- Divisor
- Pattern 5
- Pattern 10
- Overlapping Rectangles
- Nth Fibonacci Number
- Factorial of a Number
- Check Factorial
- Diamond Shape