Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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 x 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’ 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. Inside the brackets, you need to specify the lower limit, Upper Limit and the interval of the range.

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).

Please 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-

0
1
2
3
4
5

Here’s an example with the upper limit and interval specified-

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

The output-

3
5
7
9

Nested If-Statements

You can add an if 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 it doesn’t, the value of the variable ‘even’ increases by 1.

The break statement

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

I think that this should cover the topic of the for loop. Please drop a response if you have any comment, suggestion or doubt.

Check out my Medium page too!

Happy New Year,

Aarav Iyer



This post first appeared on Code Streak, please read the originial post: here

Share the post

For Loop in Python

×

Subscribe to Code Streak

Get updates delivered right to your inbox!

Thank you for your subscription

×