Loops In Python and It’s Examples

0
815
Loops In Python

Introduction To Loops In Python

Dealing with repetitive code and repetitive commands can be very hard for programmers. Python programming allows users to use loops and conditional statements to overcome this hurdle. This blog will help you to a better understanding of loops in python programming, types of loop, and its syntax.

What Are Loops In Python?

Loops in python can be used to run a group of statements multiple times. Suppose, you are a Developer and you are required to provide a software module for all the employees in your company. So, you want to print the details of the payroll of the company each employee separately. Printing the details of all the company employees will be a tiresome task, instead, you can use the logic for calculating the details and keep on repeating the same logic statement. so the loops save your time.

Loops In Python

Simple flowchart of how a loop works. If the condition is true then the control passes to the statement block and the loop iterates it by increment/decrement. If the condition is false or the all increment and decrement part are done then the loop is ended. That’s how the loop works.

What is a ‘for’ loop?

For loop is the most used loop in python programming due to its easy syntax and its predictive nature of iterative execution. A for loop has two parts, where the iteration statement is specified and then there’s the code that is executed once every iteration. A range is passed to define the number of times run code a statement is supposed to be executed using range function.

Syntax of ‘for’ loop

For value in sequence:
Body of return value
In the loop, we pass sequence in value to perform the process iteratively and take enter and give tab space then write body code.

Let us take a simple example of finding the square of a number using for loop and range function:

Example:-

for i in range(1,6):
    print(i**2)

Output:

1
 4
 9
 16
 25

A for loop is used to execute statements, the iterative process performs sequentially. The sequence could be a range, list, a Dictionary, a set, or a string.

Example 1:- Pass a string into the for loop

for letter in 'Factor':     # pass String into loop value is letter
    print(letter)          # print the character

Output:

F
 c
 a
 t
 o
 r

Example 2:- Pass list into for loop

Cities = ['Mumbai','Pune','Banglore']    # Create List

 for i in Cities:
     print(i)

Output:

Mumbai
 Pune
 Banglore

For loops using, if-else condition

This is used to applying some conditions in for loop in sequence arguments.
Suppose you want to print any statement after the sequence is over then directly use else condition. Or want to perform any logic on particular sequence value then you need to use if-else conditions.

Example 1:

for i in range(1, 3): 
    print(i) 
else:                     # After Iteration is complete then go into else 
    print("Loop End")

Output:

1
 2
 Loop End

Widget not in any sidebars

Example 2: Create List And Pass it into for loop

list1 = ['Roman','Spanish','Gujarati']

 for language in list1:
    if language == 'Roman':
        print('\nI speak ',language)
    elif language == 'Spanish':
        print('I write ',language)
    else:
        print('I love ',language)

Output:

I speak  Roman
 I write  Spanish
 I love  Gujarati

Nested loop

Perform loop inside the loop is called a Nested Loop.
The “First loop” will be run one time for each iteration of the “Second loop”

Syntex:-
for Value in sequence:
for Values in sequence:
Print(s)
Print(s)

Example:

CST = ["red", "big", "tasty"]             # List Of Color, Shape , Test
  Fruit = ["strawberry", "apple", "cherry"]   # Fruits Name

  for x in CST:                 # Iterate CST List in x
      for y in Fruit:          # Iterate Fruit list in y
        print(x, y)         # print to show output

Output:

red strawberry
 red-apple
 red cherry
 big strawberry
 big apple 
 big cherry
 tasty strawberry
 tasty apple
 tasty cherry

List Comparison using For loop

Suppose, we want to separate the characters of the word ‘DataScience’ and add the characters as items of a list. This thing happens with using for loop.

Syntex:- [ Expression for Item in List ]

Example 1: Iterating through a character Using List Comprehension

List = [ Char for Char in 'DataScience' ]    
  #List Comprehension [ letter for letter in ‘DataScience’ ]
  print( List)

Output:

['D', 'a', 't', 'a', 'S', 'c', 'i', 'e', 'n', 'c', 'e']

Example 2: Iterating through a character using for loop.

List = []                                # Blank List

 for Char in 'DataScience':     # Pass String into Loop
     List.append(Char)            # Add single character into blank list

 print(List)                              # print Updated List

Output:

['D', 'a', 't', 'a', 'S', 'c', 'i', 'e', 'n', 'c', 'e']


Widget not in any sidebars

Conclusion

In this blog, you will understand about the Loops in python, how to perform operations on a for loops in python.

LEAVE A REPLY

Please enter your comment!
Please enter your name here