Python Loops
The following loops are available in Python to fulfil the looping needs. Python offers 3 choices for running the loops. The basic functionality of all the techniques is the same, although the syntax and the amount of time required for checking the condition differ.
We can run a single statement or set of statements repeatedly using a loop command.
The following sorts of loops are available in the Python programming language.
While loop
Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.
Syntax:-
while(condition):
statement
statement
Using else Statement with while Loops
As discussed earlier in the for loop section, we can use the else statement with the while loop also. It has the same syntax.
The range() Function
With the help of the range() function, we may produce a series of numbers. range(10) will produce values between 0 and 9. (10 numbers).We can give specific start, stop, and step size values in the manner range(start, stop, step size). If the step size is not specified, it defaults to 1.
For loop
This type of loop executes a code block multiple times and abbreviates the code that manages the loop variable.
Syntax:-
for value in sequence:
{ code block }
{ code block }
Using else Statement with for Loop
As already said, a for loop executes the code block until the sequence element is reached. The statement is written right after the for loop is executed after the execution of the for loop is complete.
Only if the execution is complete does the else statement comes into play. It won't be executed if we exit the loop or if an error is thrown.
Syntax:-
for value in sequence:
{ code block }
else:
{ code block }
{ code block }
else:
{ code block }
Nested loops
We can iterate a loop inside another loop.
Break statement
This command terminates the loop's execution and transfers the program's control to the statement next to the loop.
Continue statement
This command skips the current iteration of the loop. The statements following the continue statement are not executed once the Python interpreter reaches the continue statement.