Python

Loops

Loops are an inevitably valuable asset in any programming language. It basically iterates over some code over and over until a limit is reached (for loops) or some condition is met (while loop).

Let’s say you want a certain thing to happen over and over for a number of times. In that case, we use for loops.

For Loop

A for loop in Python is constructed using the for statement and range() method.

for i in range(0, 5):
    print("Hello")

This code will print Hello five times in the console.

We can also iterate through arrays with the help of for keyword.

arr = ['Hello', 'There', 'This', 'Is', 'An', 'Array']

for i in arr:
    print(i)

This code takes the variable i and assigns the elements of the array to it, which is later printed with the print function.

While Loop

While loop is used by providing a condition to the loop then the loop is iterated over and over until the condition becomes false.

while i<10:
    print(i)
    i+=1

This code is iterated over and over only when the value of i is less than 10.

Break Statement

Now, what if you do not want to iterate the loop for a number of times but want to finish the loop before the limit is reached.

In that case, you use a break statement. As the name itself suggests, the break statement breaks the loop before it is iterated over for a certain amount of times.

while i<10:
    print(i)
    i+=1
    if i==5:
        break

This code breaks the loop when the variable i reaches a value of 5.

Continue Statement

A continue statement stops the current iteration and allows for the next iterations in the loop.

while i<10:
    i+=1
    if i==5:
        continue
    print(i)

This loop is paused over the 5th iteration when the value of i is 5 and then the loop is iterated over from the 6th iteration.

Please follow and like us:
error

Leave a Reply