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

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/python
for item in range(1, 11):
  #print(item)
  if (item % 2):
    print(str(item) + " was matched by the if statement")
  else:
    print(str(item) + " was matched by the else statement")

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee

Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





Please enter 9968b in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |