Learn Python With Dhawal -5- Chapter


CHAPTER 5

In this chapter we are going to learn more about Loops in python and how to use them in various case scenarios.

Loops in any programming language are contextually the same, as in they are a set of instructions as we say technically or a particular lines of code in layman terms, which get executed again and again.

Now, each loop has 3 main parts like variables. Loop has a declaration statement, conditional statement and an incremental factor. Since python takes off much of the programming load from the programmer and just allows us to code as if like we are playing, here we don't have to worry about the loops and their three sections for the most part but to understand how it works and how to use them we need to know the concept behind the loop.

There are basically two types of loops. (1) Entry Guarded Loop and (2) Exit guarded Loops. Obviously these aren't actual terminologies but rather conceptual terms used to understand then working of the loops. Technically they're called the control statements or entry conditions. Hence the technical terms are Entry and Exit Controlled Loops.

A set of statements which are repeatedly executed to do a certain task is called a loop. Traditionally loops are defined within the parenthesis but just like conditional statements where the bracket system is replaced with indentations, in loops too you no longer need brackets to define what's in the loop and what's out of it.

There are 3 very important and basic loops.


  1. WHILE Loop
  2. DO....WHILE Loop
  3. FOR Loop
WHILE Loop

WHILE Loop is an entry guarded loop, which means it first checks the condition, then allows the execution pointer to enter inside and start executing the statements. Once the statements are over the execution pointer moves back to the beginning of the loop and checks the condition, if it is true the same process repeats until the guarding condition becomes false and then the execution pointer is headed out of the loop towards the next statement.

In this loop you need to be careful to alter the condition once the execution of the loop begins as, if you don't make the entry condition false after your work is done, it can run till infinity and will give you a run-time error.

Syntax :

Statement xyz1
while ( condition that I want to check):
<tab>loop statement 1
<tab>loop statement 2
<tab>loop statement 3
<tab>loop statement 4
Statement xyz2


DO....WHILE Loop
In python we don't have a DO...WHILE loop but it's actually necessary to know the concept of how it works. In a DO....WHILE LOOP, its an EXIT CONTROLLED LOOP, which means it checks the condition that is used to run a loop at the end of the loop statements. This means whether the condition is true or false, the loop will at least run once and give some output. This comes out as quite useful in its own case scenarios where you need some default output even if a condition is false.

Syntax(non python pseudocode):

DO{
<tab>loop statement
<tab>loop statement
<tab>loop statement
<tab>loop statement
<tab>loop statement
}WHILE( the condition I want to check)

FOR Loop

It is one of the most used or I can say overused loops in every programming language ever. A for loop has proper three statements but all in one single line, The initiation, the control and the incremental statement. FOR Loop is also an entry controlled loop which means first there's intialistion then the condition is checked and then after executing the loop the increment is been made. There's a special type of this loop which we would use more than often in our coding tutorials further but you need to learn how the for loop functions before we actually start on using the shortcuts. Python's 'for' loop is more like 'for each' loop of other languages.

Syntax(Non-Python Psuedocode):

FOR( Initialisation, Condition, Increment ){
<tab>loop statement 1
<tab>loop statement 2
<tab>loop statement 3
<tab>loop statement 4 }

Syntax (Python):

Statement xyz1
FOR any variable name that I want in range (starting point, Ending point, step):
<tab>loop statement 1
<tab>loop statement 2
<tab>loop statement 3
<tab>loop statement 4
Statement xyz2

FOR ENHANCE LOOP

This is a special type of loop in Java but in python it is somehow used as your average for loop, where you don't have to specify anything but just the data or thing you want to run the for loop for. It'll decide everything else on its own.

Syntax:

Statement xyz1
FOR any variable name that I want in any other variable that I want to run it on :
<tab>loop statement 1
<tab>loop statement 2
<tab>loop statement 3
Statement xyz2

Now, we will learn more about it using the examples.


Code 1:

Input :

  1. counter=10;
  2. while (counter >0 ):
  3.     print ('The counter is: ',counter)
  4.     counter=counter-1

Output:

  1. The counter is:  10
  2. The counter is:  9
  3. The counter is:  8
  4. The counter is:  7
  5. The counter is:  6
  6. The counter is:  5
  7. The counter is:  4
  8. The counter is:  3
  9. The counter is:  2
  10. The counter is:  1





Here as you can see, we had a variable named counter which had an initial value of 10, I wanted to print a countdown till one hence I made a condition that counter should be greater than 0 hence the loop was executed until the value of the counter became 0. If you notice I was decreasing the value of counter by one each time. Programming follows the RHS to LHS approach in general which means that in statement 4, first it decreased the value of counter by 1 as mentioned and then assigned the new value to the counter variable.

Input :

  1. counter=10;
  2. while (counter >=0 ):
  3.     print ('The counter is: ',counter)
  4.     counter-=1

Output:

  1. The counter is:  10
  2. The counter is:  9
  3. The counter is:  8
  4. The counter is:  7
  5. The counter is:  6
  6. The counter is:  5
  7. The counter is:  4
  8. The counter is:  3
  9. The counter is:  2
  10. The counter is:  1
  11. The counter is:  0
Here, as you can see it's pretty much the same code but I changed a few lines here. The condition that I checked was less than and equal to zero which meant that now the countdown will be printed till zero. Also, the decrement statement I used a shorthand operator, usually shorthand operators are like  ++,--, in other programming languages but in python we don't have them, instead we have += and -= where we have to specify the increment or the decrement value. Since here the value is 1 it will decrease by 1, you can try out the same code by making the incremental factor 2 and reversing the countdown by printing it from 0-10 instead of 10-0. I'd like to see if you can do that or not.





Code 2:

Input :

  1. for counter in range (0,10):
  2.     print ('The counter is: ',counter)



Output:

  1. The counter is:  0
  2. The counter is:  1
  3. The counter is:  2
  4. The counter is:  3
  5. The counter is:  4
  6. The counter is:  5
  7. The counter is:  6
  8. The counter is:  7
  9. The counter is:  8
  10. The counter is:  9

As you can see here in the code above, we just printed a simply using 2 lines of code where the while took close to 4 and above to print the very same thing. This is the power of simplicity and ease that you get with python. Here, the counter variable has a starting value of 0 and ending value of 10 so the loop is run and the value of counter is incremented until it gets at 10, once it gets 10 the loop is terminated hence you'd get to see statements only from 0 to 10, if you want to print from 1 to 10 then you can use the range (1,11) to get the output. If you want to reverse then you can use the range (11,1) or range(10,0) or range (11,0). Try out your own examples of loops and ranges and see how it fairs out with you.

Input:

  1. for counter in range (2,22,2):
  2.     print ('The counter is: ',counter)
Output:

  1. The counter is:  2
  2. The counter is:  4
  3. The counter is:  6
  4. The counter is:  8
  5. The counter is:  10
  6. The counter is:  12
  7. The counter is:  14
  8. The counter is:  16
  9. The counter is:  18
  10. The counter is:  20
Here as you can see we kinda printed the table of two. Here in the range bracket we also specified the step aka the incremental factor. Here the incremental factor was +2 hence it increased the value of counter with 2 every time the loop was run. You can also make it -2 if you want to get it in the negative running from 20-2. This is how you use your usual for loops and use it to do various things.





Code 3:

Input :

  1. fruitBasket={'apple', 'banana','mango','chikoo','guava'}
  2. for fruit in fruitBasket:
  3.     print ('The fruit is: ',fruit)



Output:

  1. The fruit is:  chikoo
  2. The fruit is:  apple
  3. The fruit is:  mango
  4. The fruit is:  banana
  5. The fruit is:  guava

Here as you can see we didn't actually had to specify anything about the range or the size of the list here but still the for loop worked and printed every fruit name we had in out fruit basket list. This is usually known as the for enhance loop in other languages but here in python it's just your average for loop. I hope you try out some more examples on your own and play around with it to see how it works and what all it can take. You can use tuples instead of lists, you can use dictionary and others. Play with it yourself and find out more about it.


Note : If you are someone who is been following this course, please comment your names down below and if possible do subscribe to website for more updates, I just write more than one subject and cover a lot of areas which you might also get interested to know upon. If there's significant amount of people commenting on this post with their email and name I would surely try to make and upload a sort of course notebook with more deeper examples and things which you'd only get to learn in actual engineering classrooms. But I can do that only when the response is good, also, please comment your doubts or things that you want to know so I can cover it in the next chapters.

In Next chapter we will learn about nested loops and learn more about using them.

<< PREVIOUS CHAPTER || NEXT CHAPTER >>

~*~*~*~

This series is totally authored by me (Dhawal Joshi). Any similarities found on the text, or codes or anything is purely accidental. All the sources of reference will be mentioned, linked and will be given the proper credits. If I miss anything or there's anything wrong, feel free to comment or send me an email and I'll try to edit it out. I am not a Python expert, I am sharing whatever I have learnt on my own and with a few sources around to refer from which will be mentioned. Also feel free to share this series with others so most can benefit out of it.

~*~*~*~


Do comment and share your thoughts about it! I'd love to know what do you think. Also, I'd keep updating it quite often so do follow the Website to get all the updates by clicking here.

Also, a minor headsup.... Obsessed is free to read on Kindle Unlimited! Do check it out. I'd be glad to read your reviews!
Share :

Are you getting regular fresh content updates? If not click on the button below.

0 comments:

Post a Comment

Do comment and share your thoughts.