top of page

Python For Loop

Python loop is used to iterate over the collection or data type like string, list, tuple.

Iterate over the given list.

country = ['Germany', 'Russia', 'India', 'China']

for i in country:

    print(i)

Break Keyword

For loop will complete its iteration and stop at the end. But we can break the for loop in between and stop the iteration using a break keyword.

Break the loop when country is india.

country = ['Germany', 'Russia', 'India', 'China']

for i in country:

    print(i)

    if i == "India":

        break

Continue Keyword

For loop runs in a loop from the start of the block and goes till end. But when the loop encounter continue keyword instead of going till the end of the loop. the code will continue from the continue keyword and goes up again

continue the loop when country is india.

country = ['Germany', 'Russia', 'India', 'China']

for i in country:

    if i == "India":

        continue

    print(i)

For Else 

Like If else we do have for else and the else part of the for loop runs once the iteration gets completed.

For Else

a = ['Germany', 'Russia', 'India', 'China']

for i in a:

    print(i)

else:

    print("All countries name printed")

Key Point to Remember:

  • If for loop get break with the break keyword and didn't complete its execution then else part will not run.

  • Else part will only run when the execution of for loop is completed.

For Else

a = ['Germany', 'Russia', 'India', 'China']

for i in a:

    print(i)

    if i == "India":

       break

else:

    print("All countries name printed")

Range

range() is also an iterable object and you can use for loop to iterate over it.

Syntax : range(start,stop,step)

print numbers from 1 to 7

for i in range(1,8):

    print(i)

start and step value is optional. if you don't pass start value then python will consider 0 as start value and 1 as step value.

Break the code at number 5.

for i in range(1,8):

    print(i)

    if i == 5:

        break

bottom of page