Loops in Python

Loops in Python

Don't Repeat Yourself

Β·

5 min read

Namaste Coders!

In this article, we will discuss and learn loops in Python.

When you want to execute a block of code several times then instead of writing it again and again we can use loops that protect us from re-writing the same code. Like while listening to songs if we want to listen to a song many times then we put it on loop mode instead of playing it again and again. The flow chart shown below explains the working of loops πŸ‘‡

49.PNG

There are 2 types of loops in python:

  • for loop
  • while loop

for loop

Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. It has the ability to iterate over the items of any sequence, such as a list or a string. The syntax of using for loop in python is way different from any other programming language.

50.PNG

for iterator in iterable :
  #for statements
'''
for loops
for loops are used on iterables(list, tuple , string, range, dictionary)
'''

nums = [11,22,33,44,55,66,77]

for i in nums:
    print(i , end = ",")
#11,22,33,44,55,66,77,

name = "John Doe"

for n in name:
    print(n , end = '')
#John Doe

for i in range(5):
    print(i , end = " ")
# 0 1 2 3 4

else block in for loop

Like the else block in if statement we have else block of for loop .

num=int(input("enter a number: "))
for i in range(2,num):
    if(num%i==0):
        print("Not a prime number")
        break
else:
    print("Prime number")

Output enter a number: 5 Prime number

enter a number: 4 Not a prime number

while loop

A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true. It repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.

51.PNG

A key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Syntax

initialization

while condition:
  # statements
  re-initialization

Example

i=1
while(i<=5):
    print("number is: ",i)
    i=i+1

Output

number is: 1

number is: 2

number is: 3

number is: 4

number is: 5

Nested Loops

Python programming language allows to use one loop inside another loop. Following section shows few examples to illustrate the concept. Syntax:

for iterating_var in sequence:
    for iterating_var in sequence:
        statement(s)
    statement(s)

The syntax for a nested while loop statement in Python programming language is as follows:

while expression:
    while expression:
        statement(s)
    statement(s)

A final note on loop nesting is that you can put any type of loop inside any other type of loop. For example, a for loop can be inside a while loop or vice versa.

Printing patterns is a very good example to learn nesting:

for row in range(1,5):
    for col in range(i):
        print('*',end="")
    print()

output

*

**


The following program uses a nested for loop to find the prime numbers from 2 to 100 πŸ‘‡

i=2
while(i<100):
    j=2
    while(j<=(i/j)):
        if not(i%j): 
            break
        j=j+1

    if(j>i/j):
        print(i,"is prime")
    i=i+1

Output

2 is prime

3 is prime

5 is prime

7 is prime

11 is prime

13 is prime

17 is prime

19 is prime

23 is prime

29 is prime

31 is prime

37 is prime

41 is prime

43 is prime

47 is prime

53 is prime

59 is prime

61 is prime

67 is prime

71 is prime

73 is prime

79 is prime

83 is prime

89 is prime

97 is prime

Jump Statements

Jump statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following jump statements πŸ‘‡

  • break
  • continue
  • pass

break statement

Terminates the loop statement and transfers execution to the statement immediately following the loop.

The most common use for the break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops. If you are using nested loops, the break statement stops the execution of the innermost loop and starts executing the next line of code after the block.

52.PNG

# example 1
print("First Example")
for letter in 'Programming':
    if(letter == 'i'):
        break
    print(letter)

# example 2
print("Second Example")
num=1
while(num<5):
    if(num==3):
        break
    print(num)
    num+=1

Output First Example P r o g r a m m Second Example 1

else block while break terminating the loop

If the loop is terminated using break then else block code do not execute.

for i in range(1,6):
    if i == 3:
        break
    print(i)
else:
    print("else block statements")

Output 1 2

If break is not terminating the loop

for i in range(1,6):
    if i == 3:
        break
    print(i)
else:
    print("else block statements")

Output 1 2 3 4 5 else block statements

continue statement

It returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. The continue statement can be used in both while and for loops.

53.PNG

# example 1
print("First Example")
for letter in 'Programming':
    if(letter == 'i'):
        continue

    print(letter)

# example 2
print("Second Example")
num=1
while(num<5):
    num+=1
    if(num==3):
        continue
    print(num)

Output

First Example P r o g r a m m n g Second Example 2 4 5

Pass

It is used when a statement is required syntactically but you do not want any command or code to execute. The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go but has not been written yet.

print("First Example")
for letter in 'Programming':
    if(letter == 'i'):
        pass
        print("Pass block")

    print(letter)

Output P r o g r a m m Pass block i n g

Pass helps you to write the code later as it passes that block without showing any error as shown in the example πŸ‘†

The End

I hope you enjoyed the article and had a good learning experience.

Follow for more articles and keep sharingπŸ‘©

Keep coding

Linkedin

hashnode blogs

Did you find this article valuable?

Support akshita garg by becoming a sponsor. Any amount is appreciated!

Β