
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python3 - Why loop doesn\\\'t work?
In Python, using loops, we can execute a statement or a group of statements multiple times. Usually, the loop works for all the conditions, but there are certain scenarios where the functionality of loops is affected.
In this article, we will understand those scenarios with examples.
When sleep() method is used inside Loop
The sleep() method is defined in the time module and used to suspend or stop the execution of the program for a specified number of seconds.
When the sleep() method is placed inside a loop, it suspends the execution of each iteration for the given time. After the delay, the loop continues to execute as usual, processing the next iteration sequentially.
Example
In the following example, the for loop doesn't work or is suspended for 2 seconds for each iteration -
import time for i in range(3): print("Hello welcome to Tutorialspoint.") time.sleep(1) #suspended for one seconds print("Delay of 2sec")
Following is the output of the above code -
Hello welcome to Tutorialspoint Delay of 2sec Hello welcome to Tutorialspoint Delay of 2sec Hello welcome to Tutorialspoint Delay of 2sec
When 'continue' statement used inside a loop
The continue statement is used to skip the execution of the program based on the condition; it returns control to the beginning and starts the next iteration.
If we place the continue statement within the for loop, its execution will be suspended. We can suspend a particular iteration by using the continue statement within an if block.
Example
Here, the for loop executes for all iterations but skips the iteration where i is equal to 2 -
for i in range(5): if i==2: continue print(i)
Following is the output of the above code -
0 1 3 4