Loops in Python
Loops are used when you have a block of code which you want to repeat a fixed number of times. There are two type of loops in python:
- While Loop
- For Loop
While Loop
While loop in python is also known as pre-tested loop, because it first tests the condition then it allows the statement to execute written under it, until it is true.
For Loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). For loop is written with range function.
The Range() Function
The range is built in function in Python that allows you to generate a series of numbers within a given range. There are three ways you can call range():
- Range(stop)
- Range(start, stop)
- Range(start, stop, step)
for x in range(5):
print(x)
Output -
0
1
2
3
4
Example 2 -
for x in range(1, 5):
print(x)
Output -
0
1
2
3
4
Example 3 -
for x in range(1, 10, 2):
print(x)
Output -
1
3
5
7
9
Comments
Post a Comment
Students you can ask your doubts in comment section