Looping or iteration is fundamental to all programming languages and involves the repetition of tasks. In Python, we use the “for” loop and the “while” loop. We can create various loop types like the infinite while loop in Python with control statements like break and continue.
The Infinite Loop
A loop is a set of instructions (block) repeatedly executed as long as the defined conditions are met or satisfied. We use the while loop to repeatedly execute code blocks as long as the given condition is satisfied. The while loop has the following syntax:
while < expression > : < block >
The looping expression sets the condition based on which the loop will continue to run or terminate. In loop expressions, the variable is evaluated and repeatedly updated while the given condition is True. If not, it gets terminated.
If the expression evaluates to ‘True’ every time, it leads to an infinite loop. Let us see an example of how to make an infinite while loop in Python.
# an infinite loop
while True:
x = int(input('Enter a number: '))
print ("square of", x, "is", x*x)
Output:
Enter a number: 6
square of 6 is 36
Enter a number: 4
square of 4 is 16
Enter a number: 3
square of 3 is 9
Enter a number: 8
square of 8 is 64
Enter a number: 2
square of 2 is 4
Enter a number:
Loop With The Condition At The Top
A simple while loop does not have control statements like a break or continue. In such loops, we place the loop condition at the top. The code block under it gets executed if the condition is ‘True’. If it is not true, the loop gets terminated. We can represent this type of loop as below:
Example:
# Program to add natural
# numbers up to
# sum = 1+2+3+...+n
# To take input from the user,
n = int(input("Enter n: "))
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
If we run the program:
Enter n: 5
The sum is 15
Loop With The Condition In The Middle
We can implement this type of loop if we use a control statement like continue in the middle of the code body.
Like the break statement, the continue statement also stops the running iteration. However, instead of terminating the loop, it goes back to the loop expression for re-evaluation before continuing.
If the re-evaluated results do not comply with the expression, the loop terminates, and the program moves to the next line after the loop body. If the expression is still valid, the program continues with the next iteration.
We can represent this type of loop as below:
Let us see an example of how we can make a loop where the condition is in the middle:
w = input ('Enter a word: ')
for val in w:
if val == "a":
continue
print(val)
print("The end")
Program execution:
Enter a word: avalanche
v
l
n
c
h
e
The end
>
The above code prints all the characters of a given word except a.
Loop With The Condition At The Bottom
In Python, the break statement abruptly terminates loop execution. The loop statement sets the condition to break out of the loop. Once the program breaks out of the loop, it resumes the execution at the first line after the loop. We represent this type of loop as:
Example:
w = input ('Type a word that is less than 7 characters long: ')
letterNumber = 1
for i in w:
print ('Letter', letterNumber, 'is', i)
letterNumber+=1
if letterNumber > 7:
print('The word you have entered is more than 7 characters long!')
break
Program execution:
Type a word that is less than 7 characters long: Determinate
Letter 1 is D
Letter 2 is e
Letter 3 is t
Letter 4 is e
Letter 5 is r
Letter 6 is m
Letter 7 is i
The word you have entered is more than 7 characters long!
In the above example, the code prints all the letters of a word up to 7 characters. If you input a word that is more than 7 letters, the loop gets terminated with the final sentence.
Questions and Answers
Q1. How do you write an infinite loop in Python?
Answer: We can create infinite loops in Python via the while statement. In a loop, the variable is evaluated and repeatedly updated (while the given condition is True). We can create an infinite while loop in Python if we set the condition in a way that it always evaluates to True.
For example:
p = int(input('Enter a number: '))
while p != 0:
for q in range (1, p):
print (q)
q+=1
p = int(input('Enter a number: '))
Program execution:
Enter a number: 9
1
2
3
4
5
6
7
8
Enter a number: 4
1
2
3
Enter a number: 6
1
2
3
4
5
Enter a number:
Q2. Is the while loop infinite in Python?
Answer: A while loop is usually not infinite in Python. It only executes a code block repeatedly as long as the given condition is satisfied. The right-hand side of the expression gets evaluated first, and then the value is assigned to a variable. If the given loop condition is False, the loop is terminated or a different set of code is executed.
For example:
p = int(input('Enter your age: '))
while p < 19 or p > 60:
print('You are too young or too old to ride!')
else:
print('Welcome, you are of the right age!')
Program execution:
Enter your age: 45
Welcome, you are of the right age!
Q3. How do you make an infinite while loop?
Answer: To create an infinite while loop in Python all you have to do is make sure your conditional loop statement is always true. Let us see how we can do this through an example.
while True:
print('Python')
Output:
Python
Python
Python
Python
Python
Python
Python
Python
The code just goes on. You can interrupt the code by Ctrl + c.
Q4. Why is my for loop infinite in Python?
Answer: We cannot create an infinite loop with for statement like we do in the infinite while loop in Python. However, we can use certain functions like generator(), iter(), cycle(), etc. to create infinite for loops.
For example:
# using generator()
def generator():
while True:
yield 1
for n in generator():
print(n)
Leave a Reply