For Loop in Python

In Python, a for loop is used to iterate over a list, tuple, set, dictionary, or string.

This basically means that the interpreter will either perform a specific action on all the entities, or when used with an if-else statement, it will check if every entity in the sequence satisfies the condition or not (one by one).

For example-

a = [1, 2, 3, 4, 5, 6, 7, 8]
for i in a:
    print(x)

The output-

1
2
3
4
5
6
7
8

Here, the interpreter assigns the variable ‘x’ the value of every single entity in the list a, one at a time, and then prints it.

Strings are also iterable, and hence, you can use a for loop with a string too.

The range() function

The range() function is quite a handy thing while using for loops. The arguments accepted by it are the lower limit, upper limit and the interval or step value.

The loops then iterates through the given range and performs the required operation.

If you give only one value, the value given will be considered as the upper limit of the range. The lower limit will be taken as 0 and the interval as 1 (both are by default).

Note that the lower limit is inclusive (included in the range) while the upper limit is not.

For example-

for x in range(6):
    print(x)

The output-

1
2
3
4
5

Here’s an example with all the arguments given-

for x in range (3,11,2):
    print(x)

The output-

3
5
7
9

Nested If-Statements

You can add anif statement inside a for loop too.

For example-

odd = 0
even = 0

for x in range(1,9):
    if x % 2 == 0:
        even+=1
    else:
        odd += 1

print("The number of even numbers between 1 and 9 are", even)
print("The number of odd numbers between 1 and 9 are", odd)

The output-

The number of even numbers between 1 and 9 are 4
The number of odd numbers between 1 and 9 are 4

In this program, the interpreter checks if x, when divided by 2 leaves a remainder or not. If it does, it increases the value of the variable odd by 1. If not, the value of the variable even increases by 1.

The break keyword

The break statement can be used to stop a loop from executing (any loop). It can be used with the if-else statement too.

For example-

for x in range(6):
    if x==4:
      break
    else:
      print(x)

The output-

0
1
2
3

Here, the interpreter executes the for loop till the value of ‘x’ is 4 and then stops.

The continue statement

The continue statement can be used to stop the current iteration and continue with the rest.

For example-

for x in range(1,6):
    if x==4:
      continue
    print(x)

The output-

1
2
3
5

That is all for this post. Please drop a comment regarding any comment, suggestion or doubt.

Happy coding,
Aarav Iyer

Aarav Iyer

I am a technology and programming enthusiast, currently a high school student. I love drawing and am quite interested in aeronautics and astrophysics too. My favourite pastimes are reading books, blogging and skywatching with my telescope.

Post a Comment

Next Post Previous Post