The Python supplies the following types of loops to handle loop requirements. Python offers three ways to create traps. Although all methods provide the same basic functionality, they vary in their syntax and time to test status.
Why do we need loops?
So, In any programming language while writing codes we need some tasks to happen repeatedly under some condition. But if we will manually write all these steps one by one it will be huge and boring. So, the loops are there to repeat or perform any tasks under certain conditions.
Let us understand the need for loops in the following example.
Printing 1-15 without Using Loops
print( 0 ) print( 1 ) print( 2 ) print( 3 ) print( 4 ) print( 5 ) print( 6 ) print( 7 ) print( 8 ) print( 9 ) print( 10 ) print( 11 ) print( 12 ) print( 13 ) print( 14 ) print( 15 )
Using loops
for i in range(0,16): print(i)
So, as you notice here the length of both codes performing the same functions.
Types of loops
Generally, there are mainly three types of loops in the Python programming language and they are:
- while loop
- for loop
- nested loops
While Loops
It continues to use statements (code) as long as the condition provided is TRUE. First, check the status and then jump to the command.
Within this loop, we can have any number of statements. The situation can be anything according to our needs. The while loop stops functioning when the circumstances yield false, and the program will move to the next line of code.
count = 0
while (count < 3):
count = count + 1
print("Simitech")For loops
The for loop is used to pass the function in sequences such as lists, genres, dictionaries, sets, or strings.
These Loops statements will be used for each sequence item.
It takes the first repetitive object, extracts the statement, and then moves the cursor to the next object until it reaches the last object in sequence.
for i in range(0, 23):
print(i)Nested Loops
A loop with a nest means using a loop inside another loop. We may use any type of loop within any type of loop. We can use a temporary loop inside to make a loop, a loop inside a temporary loop, a temporary loop within a temporary loop, or a loop within a loop.
e = []
for i in range(1, 16):
while item % 2 == 0:
e.append(i)
break
print("Even Numbers: ", e)Loop control statements
Loop control statements are there to alter the implementation of the flow. These can be used if you wish to skip a repeat or stop doing it.
- break statement
- continue statement
- pass statement
Also, visit Simiservice.com
