Day #35 - For loop with else

Day #35 - For loop with else

ยท

3 min read

Introduction

Welcome to my 35th blog post. In my python coding journey, I learned about using else statements with if and nested if statements. We can also make use of the else statement with for and while loops. Now Let's dive into more details.

So let's get started......

For loop with 'else'

Python allows the use of the else keyword to be used with the for and while loops. Else block appears after the body of for and while loops. The statements in the else block will be executed after all iterations are completed. The program exits the loop only after the else block is executed.

Syntax

for counter in sequence:
    #Statements inside for loop block
else:
    #Statements inside else block

Example 1 -

for i in range(5):
  print(i)

else:
  print("Done with i counter")


#empty list, here the counter will directly jump to else 
for j in []:
  print(j)

else:
  print("Done with j counter")
0
1
2
3
4
Done with i counter
Done with j counter

Example 2 -


for h in range(5):
  print(h)
  if (h==3):
    break

else:
  print("Done with h counter")
0
1
2
3

NOTE:

In case else is executed this does not mean that the loop breaks, rather it means that the loop is successfully executed and the loop ran fully, hence the content in else is printed completely.

More Example

for x in range(5):
    print ("iteration no {} in for loop".format(x+1))
else:
    print ("else block in loop")
print ("Out of loop")
iteration no 1 in for loop
iteration no 2 in for loop
iteration no 3 in for loop
iteration no 4 in for loop
iteration no 5 in for loop
else block in loop
Out of loop

Resources Used

You can watch the video of Day#35 by clicking on the below link ๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡

Conclusion

Thanks, guys for going through this blog post. Through this Blog post, we learned about how we can use else statements with loops i.e for and while loops. I also wrote a bunch of code to practice the else statement with the loops in python.

Thank you if you read this post and have found this post useful. I hope you have joined me and are enjoying my magical journey of python coding. This is it for Day #35

See you in the next one.....


About Me

Hey Guys, I am Chintan Jain from CodeWithJain. I am a trader and content creator. I am also passionate about tech and hence wanted to explore the field of tech. I always wanted to learn to code so I watched many tutorials but procrastinated practicing coding. To get into the habit of coding consistently I am starting to BLOG with HASHNODE on daily basis.

I will document my coding journey from scratch and share my daily learnings in a blog post on HASHNODE. I hope you all will enjoy my content and my coding journey.

So what are you waiting for, smash the FOLLOW and LIKE buttons and follow along my coding journey, a step to create more beautiful digital products and empower people.


ย