Python is a general high-level programming language easy to understand and execute, it is open-source, which means it is free to use. In this article we would be discussing LOOPS IN PYTHON.
Before we go too far, let us get a basic understanding of loops, loops in Python allow us to execute a group of statements several times.
Python loops can be executed in two ways, they provide similar basic functionality but they differ in their syntax and condition-checking time.
- While Loop
- For Loop
During this article you will learn how to implement loops in the Python program and also upgrade your Python programming skillsets, this article will assist you better in understanding how and when to use loops, how to end loops and the functionality of loops in Python.
WHILE LOOP
In Python a while loop is used to execute a block of statements repeatedly until a given condition is achieved, when the condition becomes false, the line immediately after the loop is executed.
Syntax:
#python
while expression:
statement(s)
This particular loop instructs the computer to continuously execute a code based on the value of a condition.
Example of while loop:
#python program to illustrate while loop
n = 0
while (n < 3):
n = n + 1
print('This is a while loop')
Output
This is a while loop
This is a while loop
This is a while loop
Else statement with while loop in Python:
This else clause is only activated if your while condition becomes false, if you break out of the loop or an exception is raised, it won't be executed.
Here is an example of else statement with a while loop:
#python
n = 0
while (n < 3):
n = n + 1
print('This is a while loop')
else:
print('This is an else statement with a while loop')
Output
This is a while loop
This is a while loop
This is a while loop
This is an else statement with a while loop
Infinite while loop in Python
An infinite loop is a loop that keeps executing and never stops, If we want a block of code to execute an infinite number of times, we can use the infinite loop.
Example:
#python to illustrate infinite loop
count = 0
while count == 0:
print('infinite loop')
Note: It is suggested to never use this type of loop as it is a never-ending infinite loop where the condition is true, you would have to forcefully terminate the compiler. To avoid this issue, it's a good idea to take a moment to consider the different values a variable can take. This helps you make sure the loop won't get stuck during iteration.
FOR LOOP
A for loop iterates over a sequence of values. In Python, there is a "for in" loop which is similar to the "for each" loop in other programming languages.
Syntax
#python
for iterator_val in sequence:
statement(s)
It can be used to iterate over a range and iterators
Example:
#python
for i in range(5):
print(i)
Output
0
1
2
3
4
Well, the power of the for loop is that we can use it to iterate over a sequence of values of any type, not just a range of numbers. For example, we can iterate over a list of strings or words:
#python
friends = ['Tommy', 'Johnny',' Mike']
for name in friends:
print('Hello',name)
Hello Tommy
Hello johnny
Hello Mikey
The sequence that the For loop iterates over could contain any type of element, not just strings. For example, we could iterate over a list of numbers to calculate the total sum and average.
Example:
#python
values = [2,3,4,5,60,30]
sum, length = 0, 0
for value in values:
sum += value
length += 1
print('TOTAL SUM: ' + str(sum) + ' AVERAGE: ' + str(round(sum/length,2)))
Output
TOTAL SUM: 104 AVERAGE: 17.33
Else statement with for loop in Python:
We can also combine the else statement with FOR loop like in the 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.
Example:
#python
# Python program to illustrate
# combining else with for
list = ["book", "for", "book"]
for index in range(len(list)):
print(list[index])
else:
print("Inside Else Block")
Output:
book
for
book
Inside Else Block
HOW TO IDENTIFY WHAT TYPE OF LOOP TO USE:
If you are wondering when you should use FOR and WHILE loops, there is a way to tell;
- Use FOR loops when there is a sequence of elements that you want to iterate.
- Use WHILE loops when you want to repeat an action until a condition changes.
NESTED LOOPS
A nested loop is one or more FOR loops inside another loop.
Syntax:
#python
for iterator_var in sequence:
for iterator_var in sequence:
statement(s)
statement(s)
The syntax for a nested while loop in Python programming:
#python
while expression:
while expression:
statement(s):
statement(s):
Example:
# Python program to illustrate
# nested for loops in Python
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
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.
Example:
#python
# Prints all letters except 'o' and 'k'
for letter in 'bookforbook':
if letter == 'o' or letter == 'k':
continue
print('Current Letter :', letter)
Output:
Current Letter : b
Current Letter : f
Current Letter : r
Current Letter : b
Break Statement
The BREAK statement in Python brings control out of the loop.
Example:
#python
for letter in 'bookforbook':
# break the loop as soon it sees 'o'
# or 'k'
if letter == 'o' or letter == 'k':
break
print('Current Letter :', letter)
Output:
Current Letter : o
Pass Statement
#python
# An empty loop
for letter in 'bookforbook':
pass
print('Last Letter :', letter)
Output:
Last Letter : k
Common Mistakes With Loops In Python
Iterating over non-sequences: As Iβve mentioned already, for loops iterate over sequences. Consequently, Pythonβs interpreter will refuse to iterate over single elements, such as integers or non-iterable objects.
Failure to initialize variables. Make sure all the variables used in the loopβs condition are initialized before the loop.
Unintended infinite loops. Make sure that the body of the loop modifies the variables used in the condition so that the loop will eventually end for all possible values of the variables.
Forgetting that the upper limit of a range() isnβt included.
How does For loop in Python works internally?:
Before proceeding to this section, you should have a prior understanding of Python Iterators.
Firstly, let's see what a simple for loop looks like.
#python
# A simple for-loop example
fruits = ["apple", "orange", "kiwi"]
for fruit in fruits:
print(fruit)
Output:
apple
orange
kiwi
Here we can see the for loops iterates over iterable object fruit which is a list. Lists, sets, and dictionaries are few iterable objects while an integer object is not an iterable object. For loops can iterate over any of these iterable objects.
Now with the help of the above example, letβs dive deep and see what happens internally here.
- Make the list (iterable) an iterable object with the help of the iter() function.
- Run an infinite while loop and break only if the StopIteration is raised.
- In the try block, we fetch the next element of fruits with the next() function.
- After fetching the element we did the operation to be performed with the element. (i.e print(fruit))
#python
fruits = ["apple", "orange", "kiwi"]
# Creating an iterator object
# from that iterable i.e fruits
iter_obj = iter(fruits)
# Infinite while loop
while True:
try:
# getting the next item
fruit = next(iter_obj)
print(fruit)
except StopIteration:
# if StopIteration is raised,
# break from loop
break
Output:
apple
orange
kiwi
Conclusion:
In this article, I explained how to tell a computer to do an action repetitively. Python gives us three different ways to perform repetitive tasks: while loops, for loops.
For loops are best when you want to iterate over a known sequence of elements but when you want to operate while a certain condition is true, while loops are the best choice.
Top comments (7)
Hi! I just finished reading your latest article and I have to say, it's quite well-written. Keep up the good work!
Also, welcome to the community! It's always great to have new members who are passionate about the same things as we are. Looking forward to reading more of your work.
Just a heads up that you can add highlighting to the code blocks if you'd like. Just change:
... to specify the language:
More details in our editor guide!
Thank you very much, I would definitely work on that now
This is interesting to read though Iβm not into to python but I can relate as python have similar syntax with JavaScript
You are a good writer βοΈ
Thank you for the supportive comment
Thanks for Giving information 8171
Nice writing
Thank youu