Python for Loop
Overview
The for loop in Python is used to iterate over a sequence (list, tuple, string, dictionary) or other iterable objects. Iterating over a sequence is called traversal.
Syntax of for loop
for i in iterator:
# statements
Here the iterable is a collection of objects like list, tuple. The indented statements inside the for loops are executed once for each item in an iterable. The variable var takes the value of the next item of the iterable each time through the loop.
Example:
#Print all numbers from 0 to n.
n = int(input())
for i in range(n + 1):
print(i)
output:
5
0
1
2
3
4
5
Python range() function
Below is the syntax of the range() function.
range(start, stop,step)
It takes three arguments. Out of the three, two are optional. The start and step are the optional arguments.
Parameters
8.
Points to remember
- The range() function only works with the integers, So all arguments must be integers. You can not use float numbers or any other data type as a start, stop, and step value.
- All three arguments can be positive or negative.
- The step value must not be zero. If a step=0, Python will raise a ValueError exception.
range(start, stop)
When you pass two arguments to the range(), it will generate integers starting from the start number to stop -1.
Example:
for i in range(10,15):
print(i)
output:
10
11
12
13
14