Loops construction in Python for Beginners

Now, we move ahead. Looping is a majorly used concept in programming. A loop statement allows executing a statement or group of statements multiple times. In Python, indentation is important in loop and other control statements. In Python, they are two types of loops

  • for loop
  • while loop

In a real-life example, In school days we did at least one wrong. At the time, Mam gave punishment for write a question 100 times. we experienced on these. This is an example of looping. But we are proud to be Computer students. we write one time then we achieved 100 times using looping.

for loop

for loop is the most comfortable loop. It is also an entry check loop. The condition is
checked in the beginning and the body of the loop(statements-block 1) is executed if it is only
True otherwise the loop is not executed.

Syntax of for loop:

for counter_variable in sequence:
statements-block 1

In Python, for loop uses the range() function in the sequence to specify the initial, final, and increment values. range() generates a list of values starting from start till stop-1.

The syntax of range() is as follows: In range function final is important to specify. That is final value is compulsory.

range (start,stop,step)
Where,
start – refers to the initial value. # Default by 0.
stop – refers to the final value.
step – refers to increment value. # Default by 1

python virtual image

while loop

while loop also entry check loop. If the condition is true it executes the statement until the condition gets false. Its working procedure is also the same as for loop. One of the main advantages of for loop, it generates a range() function but it is not done by using a while loop.

Syntax of while loop:

while :
    statements block 1

else part is optional for both for and while If you want else part you can add otherwise it’s optional.

python virtual image

That the control variable is i, which is initialized to 0, the condition is tested i<=5, if true value of i gets printed, then the control variable i get updated as i=i+1 (this can also be written as i +=1 using shorthand assignment operator). When I become 1, the condition is tested False and this will terminate the loop.

My Previous Post:

Control structures in Python: https://iterathon.tech//introduction-to-control-structures-in-python/

LEARN LITTLE BY LITTLE TO CHANGE THE TECH WORLD


Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *