Python (Scripting) - Looping over a sequence of integers using range

by
Jeremy Canfield |
Updated: November 06 2023
| Python (Scripting) articles
range can be used to loop over a sequence of integers.
#!/usr/bin/python
for item in range(5):
print(item)
This most basic script should output 0 through 4.
0
1
2
3
4
You can specify the beginning integer (0 in this example) and the ending integer (5 in this example).
#!/usr/bin/python
for item in range(1, 5):
print(item)
Which should output 1 through 4.
1
2
3
4
You can specify the count that should be incremented in each loop (2 in this example).
#!/usr/bin/python
for item in range(1, 10, 2):
print(item)
Which should output the following.
0
2
4
6
8
Or you could use an if else statement to match every other result.
#!/usr/bin/python3
for item in range(1, 11):
#print(item)
if (item % 2):
print(f"{item} was matched by the if statement")
else:
print(f"{item} was matched by the else statement")
Did you find this article helpful?
If so, consider buying me a coffee over at