Python for loop

for loop is used for iterating over a sequences. In python it works in the same way as it works in other programming languages. Python for loop

With the for loop we can execute set of instructions , once for each item in a list, tuple, set etc.

Syntax:

for value in sequence:
    # statement(s)

Example:

sports = ["cricket", "football", "chess"]
for x in sports:
  print(x)
cricket
football
chess

Example 2:

Loop through the letters

for x in "Fullstackadda":
  print(x)
F
u
l
l
s
t
a
c
k
a
d
d
a

Example 3:

marks = [35, 80, 75, 48, 59]
for x in marks:
  print(x)
35
80
75
48
59

Python range() function:

range() is a built-in function of Python. It is used when a user needs to perform an action for a specific number of times. 

In simple terms, range() allows user to generate a series of numbers within a given range.

range() takes mainly three arguments.

  • start: integer starting from which the sequence of integers is to be returned
  • stop: integer before which the sequence of integers is to be returned.
    The range of integers end at stop – 1.
  • step: integer value which determines the increment between each integer in the sequence

Example:

Example using range() function

for i in range(10):
	print(i, end=" ")
0 1 2 3 4 5 6 7 8 9 

Example 2:

Example using custom selection range.

for i in range(5, 10):
	print(i, end=" ")
5 6 7 8 9

Note: In the above code start point is 5(start = 0) and the stop point is 10(stop = 10). Indexing starts from “0” so 10 is excluding in the output.

fullstackadda/pointstoremember33
  1. For loop is used for iterating over a sequences. 
  2. range() is a built-in function of Python. It is used when a user needs to perform an action for a specific number of times.