Python Loops

Python loop is a concept in python programming where a block of statements repeats itself until it satisfies a particular situation or reaches a specified point. The main use for working with loops is to facilitate cycling with different values, to perform mathematical operations easily such as addition, subtraction, etc. in a list, repeating functions, etc. Another major use of loops in python is to search for information within the given data types feasibly. In this article, we will learn about what loops actually are, how loops work in python, different types of loops compatible with python with their program codes, looping through multiple lists, looping control statements, and looping through strings, etc. Let us start learning the concepts of python loops in detail and working on them.

What are Loops

When we talk about loops, a loop is basically a set order of instructions that keep on repeating until given an argument to stop or specified an arrangement for start and end. This process is done where a particular condition is examined on fetching the data of the object and the loop is then applied to it. For example, loops are used to check if a counter has reached a designated position or not.

Loops in Python

Loops as explained above, perform the same function in python programming as well. Python has different types of loops to manage the looping requirements. The three main loops to work with are for loop, if-else loop, and while loop. All these loops provide the same functionality however they tend to differ in the syntax and the checking time of a particular condition.

Become a Python Certified professional by learning this HKR Python Training!

Advantages of Loops

  • Loops increase the reusability of the code in python
  • The loops make the work of a user easy as he does not need to write the same code again and again.
  • The loops also make traversal easy while coding with arrays or linked lists. 

Types of Loops

There are 3 types of loops in python:

  • ‘for’ loop
  • ‘while’ loop
  • ‘if-else’ loop

Let us now understand each loop in detail one by one.

For Loop

A user uses the ‘for’ loop in python to perform iterations over a sequence which can possibly be a list, dictionary, a tuple, a string, etc. The ‘for’ keyword is not actually used like a ‘for’ to code in various programming languages; however, it is more of an iterator method in which a user can observe other object-oriented programming languages.

Below is the basic syntax for running for loop inside a python code:

for val in list:

loop body

Here val is basically the variable that can take the value of the object inside the order of every iteration of the loop. The process continues until the user reaches the last point while iterating. Now, We will see in the example below how the ‘for’ loop is separated from the rest of the code using indentation.

numbers = [3, 6, 9, 5, 4, 1, 2, 4, 11, 15]

sum = 0

for val in numbers:

    sum = sum+val

print("The sum of the number will be", sum)
Output:
The sum of the number will be 60

While Loop

A user can work with a ‘while’ loop to perform iterations within a block of code unless the condition of the given argument is true. This loop is used when the user is not sure about the number of times he wants to iterate over the list or tuple.

Below is the basic syntax for running the ‘while’ loop inside a python code:

while expression:

    loop body

A user has to make sure that he always tests the expression before working on it. The expression has to be TRUE then only the body of the loop is entered further. All the non-zero values are evaluated to TRUE in python. This is performed after every iteration until the expression returns FALSE. A false expression is basically no value or a zero. The body of the while loop in python will always be resolved using indentation.

Let us see a python code below to understand how the ‘while’ loop works in python:

x = 15

sum = 0

i = 1

while i <= x:

    sum = sum + i

    i = i+1    

print("The sum will be", sum)
Output:
The sum will be 120

if-else Loop

A user needs to make certain decisions while working with numbers. Let's say: If this then that means if a user needs to decide if he gets a number 4, he will roll the dice. Similarly, in programming languages, there might be a situation where the user wants to make certain decisions. Hence, an if-else loop is used where decision-making has to be done. The code only gets executed if the argument is satisfied.

Below is the basic syntax for running the ‘if-else’ loop inside a python code:

if (argument):

    # will execute if block only when the argument is true

else:

    # will execute if block only when the argument is false

Let us see a python code below to understand how ‘if-else’ loop works in python:

i = 15

if (i < 10):

    print("i is smaller than 10")

    print("The element is present in the if block")

else:

    print("i is greater than 15")

    print("The element is present in the else block")

print("The element is not present in any block")
Output:
i is greater than 15

The element is present in the else block

The element is not present in any block

>

In the above example, the python code after the ‘if’ block is only executed because the required condition was present in the statement will not be true after calling the argument absent from the block.

Let us see another python code where the if-else loop is applied to list comprehension arguments in python:

def Sumofdigits(x):

digisum = 0

for ele in str(x):

digisum += int(ele)

return digisum

 

List = [100, 200, 300, 400, 500, 600, 700]

LatestList = [Sumofdigits(y) for y in List if y & 100]

print(LatestList)
Output:
[1, 2, 3, 4, 5, 6, 7]

>

Python Training Certification

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

Nested Loops

Nested if-Loop

It is possible to have another condition statement inside an if-else statement. Moreover, there can be an infinite number of ‘if’ inside the main-if-else statement. We call this whole process nested programming in computer languages. The only way to figure out nesting is by using indentation. Sometimes, it is very confusing for the programmers to use nested loops, hence they can be avoided depending on the type of code.

Let us see a python code to understand the use of nested if inside the if-else loop.

num = float(input("Enter the number: "))

if num >= 0:

    if num == 0:

        print("Zero")

    else:

        print("It is a positive number")

else:

    print("It is a negative number")
Output:
Enter the number: 5

It is a positive number

Loop Control Statements

Loop control statements are the ones that can change the code execution from its normal order form. Hence, all the objects created within that scope are demolished when execution leaves the scope. In Python, there are 3 types of loop control statements:

  • continue statement
  • break statement
  • pass statement

Let us talk about these all one by one.

Continue Statement

In python, the ‘continue’ statement returns the control of the statement to the beginning of the loop. Or we can say that it will simply pass the control to the next iteration of the closest statement, bypassing any remaining statements.

Let us see a python code to understand how we can use the ‘continue’ statement inside a loop.

for val in "HKR Trainings":

    if val == "i":

        continue

    print(val)

 

print("END")
Output:
H

K

R

 

T

R

a

n

n

g

s

END

In the code above, the program continues with the loop as mentioned and does not take the ‘i’ alphabet from the block. It keeps executing the rest of the block.

Break Statement

In python, the ‘break’ statement will bring the control out of the loop. This statement will also terminate the statement of the loop and shift the execution to the immediate statement.

Let us see a python code to understand how we can use the ‘break’ statement inside a loop.

for val in "HKR Trainings":

    if val == "i":

        break

    print(val)

print("END")
Output:
H

K

R

 

T

r

a

END

In the code above, the program terminates the execution of the loop as it finds the ‘i’ alphabet from the block. It will stop the execution of the rest of the code block.

Pass Statement

In python, the ‘pass’ statement is used to write the empty loops only. We can also use it for the execution of empty control statements.

Let us see a python code to understand how we can use the ‘pass’ statement inside a loop.

for val in "HKR Trainings":

    if val == "i":

        pass

    print(val)
Output:
H

K

R

 

T

r

a

i

n

i

n

g

s

>

In the code above, the program continues simply and executes the empty loop.

Looping Through Multiple Lists

A user can perform Iterations over single lists by making the use of loops on a single item in a single list in each step. However, in multiple lists, the user makes use of ‘for’ loops over a single item of multiple lists. Simultaneous iterations can be done in 2 ways in python:

zip(): zip is a method that returns an iterator in Python 3. It will stop when one list out of all the given lists gets exhausted. In other words, we can say that the zip() method runs to the smallest amongst all the provided lists.

Let us see a python code below to understand how zip() method is executed:

import itertools

num = [10, 20, 30]

colour = ['pink', 'while', 'red']

value = [250, 256]

for (x, y, z) in zip(num, colour, value):

print (x, y, z)
Output:
10 pink 250

20 while 256

>

Subscribe to our youtube channel to get new updates..!

itertools.zip_longest(): This process tends to stop when all of the lists are finished. When the shortest iterator is finished, zip_longest will create a tuple having value = None in it.

If you want to Explore more about Python? then read our updated article - Python Tutorial.

Let us see a python code below to understand how zip-longest() method is executed:

import itertools

num = [10, 20, 30]

color = ['pink', 'while', 'red']

value = [250, 256]

for (x, y, z) in itertools.zip_longest(num, color, value):

print (x, y, z)
Output:
10 pink 250

20 while 256

30 red None

Looping Through String

In python, it is possible for the user to perform multiple operations on a string. Iteration is one of the processes out of all.

Let's understand the code below, and how iteration over strings is possible using loops.

# Code 1: Iterate over String

string_name = "Welcome to HKR"

for x in string_name:

print(x, end=' ')

 

string_name = "Welcome to HKR"  

# Code 2: Iterate over Index

string_name = "HKR"

  

# Iterate over index

for x in range(0, len(string_name)):

    print(string_name[x])
Output:
W e l c o m e   t o   H K R

H

K

R

This can also be done using the enumerate() function in python. Let us see another code below to understand how it works:

string_name = "Welcome to HKR"

for i, x in enumerate(string_name):

print(x)
Output:
W

e

l

c

o

m

e

 

t

o

 

H

K

R

>

Python Training Certification

Weekday / Weekend Batches

Conclusion

In this article, we have deeply understood how python works with loops. We have 3 main loops in python which are the ‘for’ loop, ‘if-else’ loop, and ‘while’ loop. Loops play a major role while coding as they make it easier for the programmer to loop instead of writing the same code again and again.

Related Articles

1. Alteryx VS Python

2. Golang Vs Python

3. Power BI With Python

Find our upcoming Python Training Certification Online Classes

  • Batch starts on 1st Dec 2022, Weekday batch

  • Batch starts on 5th Dec 2022, Weekday batch

  • Batch starts on 9th Dec 2022, Fast Track batch

Global Promotional Image
 

Categories

Request for more information

Gayathri
Gayathri
Research Analyst
As a senior Technical Content Writer for HKR Trainings, Gayathri has a good comprehension of the present technical innovations, which incorporates perspectives like Business Intelligence and Analytics. She conveys advanced technical ideas precisely and vividly, as conceivable to the target group, guaranteeing that the content is available to clients. She writes qualitative content in the field of Data Warehousing & ETL, Big Data Analytics, and ERP Tools. Connect me on LinkedIn.