Python 3-Loops

Python For loop

Python for loop is used to iterate different types of data types such as List and Tuples in sequence.

Example:

input_list = [10,20,30,40]
for x in input_list:
    print(x)

Output:

10
20
30
40

From the above example, input_list is the list contains numbers, x is the temporary variable which is used for iteration and print(x) prints the value of x on each iteration

Enumerate() in Python for loop:

When dealing with iterators in for loop, we need to keep the count of iterations. This can be achieved using Enumerate() method which adds a counter to a iterable and returns it in a form of enumerate object. This enumerate object can be directly used in for loops or be converted into a list of tuples() using list() method.

Input_data = ["apple", "banana","strawberry"]
for x, y in enumerate(Input_data):
    print(x)
    print(y)

Output:

0
apple
1
banana
2
Strawberry

Conditional statements within for loop:

Conditional statements if/else can be used within for loops for the conditional based for loops.

There is few drawbacks while using the conditional statements within for loop. We use return and continue statements in for and while loops to overcome the drawback. Let’s check the following example

Example:

Input_data = "rabbit"
for x,y in enumerate(Input_data):
    if x == "b":
        print("B available")
    else:
        print("B not available")

Output:

B not available
B not available
B available
B available
B not available
B not available

From the above example, it is unnecessary to print the else statement once the condition is true. The main drawback for above code is that it consumes unwanted memory and time. To avoid this, we use break statement which helps to stop the looping

Example for break statement:

Input_data = ["apple", "banana", "strawberry", "mango"]
for x in Input_data:
    if x == "banana":
        print("My favourite is " , x)
        break
    else:
        print("please loop again")

Output:

please loop again
My favourite is  banana

Opposite to break statement is continue. Instead of breaking from the condition, it simply continues to the loop.

Example for continue statement:

x = [1,2,3,4]
 for i in x:
     if i == 1:
             continue
     print(i)

Output:

2
3
4

In above example, the continue statement, continue the loop and will not print the value for that index.

 

Python While Loops:

As long as the condition is “True”, the loop gets executed continuously.

Example:

 x = 1
 while x<5:
     print("looping")
     x += 1

Output:

looping
looping
looping
looping

From the above example, based on the condition at while, the loop breaks when the condition fails. If there is no increment option, then entire loop will traverse for n number of times.

We can also use break and continue statements in while loop similar to for loop.