Loops In Python
A loop allows us to execute a group of statements several times. Loops are often used on algorithms.
There are some types of loops in python:
- for loop
- while loop
- nested loops
For Loop
A ‘for loop’ is used to execute statements once every iteration. We already know the number of iterations that are going to execute.
A for loop has two blocks, one is where we specify the conditions and then we have the body where the statements are specified which gets executed on each iteration.
for x in range(10):print(x)
While Loop
The while loop executes the statements as long as the condition is true. We specify the condition at the beginning of the loop and as soon as the condition is false, the execution stops.
i = 1while i < 6:print(i)i += 1#the output will be numbers from 1-5.
Nested Loops
Nested loops are a combination of loops.
Following are a few examples of nested loops:
for i in range(1,6):for j in range(i):print(i , end = "")print()# the output will be122333444455555
Conditional and Control Statements
Conditional statements in python support the usual logic in the logical statements that we have in python.
Following are the conditional statements that we have in python:
- if
- elif
- else
if statement
x = 10if x > 5:print('greater')
The if statement tests the condition, when the condition is true, it executes the statements in the if block.
elif statement
x = 10if x > 5:print('greater')elif x == 5:print('equal')#else statementx =10if x > 5:print('greater')elif x == 5:print('equal')else:print('smaller')
When both if and elif statements are false, the execution will move to else statement.
Control statements
Control statements are used to control the flow of execution in the program.
Following are the control statements that we have in python:
- break
- continue
- pass
break
name = 'edureka'for val in name:if val == 'r':breakprint(i)#the output will beedu
The execution will stop as soon as the loop encounters break.
Continue
name = 'eduard'for val in name:if val == 'r':continueprint(i)#the output will beeduard
When the loop encounters continue, the current iteration is skipped and the rest of the iterations get executed.
Pass
name = 'eduardo'for val in name:if val == 'r':passprint(i)#the output will beeduardo
The pass statement is a null operation. It means that the command is needed syntactically but you do not wish to execute any command or code.
Now that we are done with the different types of loops that we have in python, let's understand the concept of functions in my next post.