For loop ( Fixed or definite Iteration, Count-controlled loop):

M3-R5.1 · Chapter 4: Operators, Expressions and Python Statements · 2 min read

For loop ( Fixed  or definite Iteration, Count-controlled loop):  For loop in Python, which is used to repeat a block of code a specific number of times or to loop through a collection like a list or string. OR

      A for loop in Python is used to iterate over sequences like lists, tuples, dictionaries, sets, or strings. It allows executing a block of code multiple times.

NOTE: The "while" Loop is used when a condition needs to be verified after each repetition or when a piece of code needs to be repeated indefinitely. The for Statement is opposed to this Loop.

Syntax of for Loop

Flow Chart of For Loop

Explanation of for Loop Syntax-1:

  • The first word of the statement starts with the keyword “for” which signifies the beginning of the for loop.
  • Then we have the iterator variable Name (suppose i) which iterates over the sequence and can be used within the loop to perform various functions
  • The next is the “in” keyword in Python which tells the iterator variable to loop for elements within the sequence
  • And finally, we have the sequence variable which can either be a list, a tuple, or any other kind of iterator.
  • The statements part of the loop is where you can play around with the iterator variable and perform various function

Note: The for loop does not require an indexing variable to set beforehand, as the for command itself allows for this

Example 1: Sequence In For Loop

word = "Hello"

for ch in word:

    print(ch)

name = "Python"

for ch in name:

    print(ch)

for i in [0,1,2,3]:

    print(i)

for i in n[1,3,5,7,9]:

    print(i*i)

    print(i ”*”, end=” “)