Python Programming (136 Blogs) Become a Certified Professional
AWS Global Infrastructure

Data Science

Topics Covered
  • Business Analytics with R (26 Blogs)
  • Data Science (20 Blogs)
  • Mastering Python (86 Blogs)
  • Decision Tree Modeling Using R (1 Blogs)
SEE MORE

Loops In Python: Why Should You Use One?

Last updated on Nov 27,2024 15.1K Views

25 / 62 Blog from Python Fundamentals

Dealing with redundant code and repetitive commands can be a nightmare for any programmer. Python makes use of loops, control and conditional statements to overcome this hurdle. This article will help you understand loops in python and all the terminologies that surround loops.

If you want to master the concepts of loops in Python by Certified Python Expert, you can check out the below video where these topics are covered on a broader gauge

Python Loops Tutorial | Python For Loop | While Loop Python | Python Training | Edureka

This Edureka “Python Loops” tutorial will help you in understanding different types of loops used in Python. You will be learning how to implement all the loops in python practically.

What Are Loops In Python? 

Loops in Python allow us to execute a group of statements several times. Lets take an example to understand why loops are used in python.

Suppose, you are a software developer and you are required to provide a software module for all the employees in your office. So, you must print the details of the payroll of each employee separately. Printing the details of all the employees will be a tiresome task, instead you can use the logic for calculating the details and keep on iterating the same logic statement. This will save your time and make your code efficient.

The illustration below is the flowchart for a loop:   

flowchart for a loop-loops in python-Edureka

The execution starts and checks if the condition is True or False. A condition could be any logic that we want to test in our program. If its true it will execute the body of the loop and if its false, It will exit the loop.

Conditional Statements

Conditional statements in Python support the usual logical conditions from mathematics.

For example:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to : a >= b

These statements can be used in several ways, most commonly in if statement.

Let us understand the concept of if statements.

You can even check out the details of successful Spark developer with the PySpark online course.

‘if’ Statement

An if statement is written using the ‘if’ keyword, The syntax is the keyword ‘if’ followed with the condition.

Below is the flowchart of the if statement:

flowchart of if-loops in python-Edureka     

As you can see, the execution encounters the if condition and acts accordingly. If it is true, it executes the body and if it is false, it exits the if statement. 

a = 10
b = 20
if a < b :
print(" b is greater")

Above code snippet illustrates the basic example of how a condition is used in the if statement. 

When it reaches the if statement it checks whether the value of b is greater or not. If b is greater, it prints “b is greater“. Now if the condition is false, it exits the if statement and executes the next statement. In order to print the next statement, we can add a keyword ‘else’ for the alternate result that we wish to execute. Lets move to the else statement for better understanding.

‘else’ Statement

The else keyword catches anything that is not caught by the preceding conditions. When the condition is false for the if statement, the execution will move to the else statement.

Lets take a look at the flowchart of else statement below:

 

flowchart of else-loops in python-Edureka

As you can see, when the if statement was false the execution moved to the body of else. Lets understand this with an example.

a = 10
b = 20
if a < b :
print(" b is greater")
else:
print(" a is greater")

The first condition is not true, so we will move to the next statement which is the else statement and print “b is greater”.

In case we have more conditions to test, we can also use elif statement.

‘elif’ Statement

elif statement in layman term means “try this condition instead”. Rest of the conditions can be used by using the elif keyword.

Let us look at the code below:

a = 10
b = 20
if a < b :
print(" b is greater")
elif a == b :
print(" a is equal to b ")
else:
print(" a is greater")

“When the if statement is not true, the execution will move to the elif statement and check if it holds true. And in the end the else statement if and elif are false.

Since a != b, “b is greater” will get printed here.

Note: python relies on indentation, other programming languages use curly brackets for loops.

What Is ‘for’ Loop and ‘while’ Loop

  flowchart of a for loop-loops in python-Edureka

A for loop is used to execute statements, once for each item in the sequence. The sequence could be a list, a Dictionary, a set or a string.

A for loop has two parts, the block where the iteration statement is specified and then there is the body which is executed once every iteration.

Unlike while loop, we already specify the number of times the iterations must execute. for loop syntax takes three fields, a Boolean condition, initial value of the counting variable and the increment of the counting variable.

Look at the example to understand this better:

days = ["sun" , "mon" , "tue" , "wed", "thu", "fri", "sat"]
for x in days:
print(x)

Here we were iterating through the list. To iterate through a code for a specified number of times we could use the range() function.

Range Function

Range function requires a specific sequence of numbers. It starts at 0 and then the value increments by 1 until the specified number is reached.

For example:

for x in range(3)
print(x)

It will print from 0-2, the output will look like

0 
1
2

Note: the range (3) does not mean the values from 0-3 but the values from 0-2.

Below is another example using the condition statements:

example-loops in python-Edureka

 

num = int(input("number"))

factorial = 1
if num < 0 :
print(" invalid input")
elif num == 0:
print(" factorial is 1")
else:
for i in range( 1 , num+1):
factorial = factorial * i
print(factorial)

‘while’ Loop

The ‘while’ loop executes the set of statements as long as the condition is true.

It consists of a condition block and the body with the set of statements, It will keep on executing the statement until the condition becomes false. There is no guarantee to see how long the loop will keep iterating.

Following is the flowchart for while loop:

flowchart of while-loops in python-Edureka

To understand this let’s take a look at the example below.

Example:

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

Output: it will print 1 2 3 4 5

The execution will continue until value of i reaches 6.

The while loop requires the relevant variable to be ready, here we need an indexing variable, which could be any value.

Lets consider another example:

example-loops in python-Edureka

num = int(input("enter number"))
while num > 0:
    if num < 13:
        print("the number is too large")
        break
    elif num < 13:
        print("number too small")
        break
    elif num == 13:
        print("exit: congratulations")
        break

Note: remember to iterate i or the loop will continue forever. if there is no control statement here, loop will continue forever. try removing the break statement and run again.

We might need to control the flow of the execution to favor a few conditions in some cases, so let’s understand the loop control statements in Python.

Loop Control Statements

To control the flow of the loop or to alter the execution based on a few specified conditions we use the loop control statements discussed below. The control statements are used to alter the execution based on the conditions.

In Python we have three control statements:

Break

Break statement is used to terminate the execution of the loop containing it. As soon as the loop comes across a break statement, the loop terminates and the execution transfers to the next statement following the loop.

flowchart of break-loops in python-Edureka

As you can see the execution moves to the statement below the loop, when the break returns true.

Let us understand this better with an example:

for val in "string" :
    if val == "i":
       break
       print(val)
    print("the end")

                                 
Output:

s
t
r
The end

Here the execution will stop as soon as the string “i” is encountered in the string. And then the execution will jump to the next statement.

 

Continue

The continue statement is used to skip the rest of the code in the loop for the current iteration. It does not terminate the loop like the break statement and continues with the remaining iterations.

flowchart of continue-loops in python-Edureka

When continue is encountered it only skips the remaining loop for that iteration only.

For example:

for val in "string" :
    if val == "i":
       continue
       print(val)
   print("the end")
Output: 
s
t
r
n
g
the end

It will skip the string “i” in the output and the rest of the iterations will still execute. All letters in the string except “i” will be printed.

Pass

The pass statement is a null operation. It basically means that the statement is required syntactically but you do not wish to execute any command or code.

Take a look at the code below:

for val in "please":
if val == "a":
   pass
   print("pass block")
   print(val)

Output:

p 
l
e
pass block
a
s
e

The execution will not be affected and it will just print the pass block once it encounters the “a” string. And the execution will start at “a” and execute the rest of the remaining iterations.

‘while’ Loop Using The Break Statement

Lets understand how we use a while loop using a break statement with an example below:

i = 1
while i < 6 : 
     print(i)
     if i == 3 :
        break
        i += 1

Output: it will print 1 2

The execution will be terminated when the iteration comes to 3 and the next statement will be executed.

Using Continue Statement

Let’s take an example for continue statement in a while loop:

i = 1 
while i < 6: 
   print(i)
   if i == 3 :
      continue
      i += 1

Output: 1 2 4 5

Here the execution will be skipped, and the rest of the iterations will be executed.

Nested Loops

Python allows us to use one loop inside another loop, Following are a few examples

Nested for loop

An example to use a for loop inside another for loop:

for i in range(1 , 6):
  for j in range(i):
     print( i , end="")
   print()

Output:

1
2 2
3 3 3
4 4 4 4

Nested ‘while’ loop

Below is the basic syntax to use a nested while loop:

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

Example:

An example to show a nested while and for loop:

travelling = input("yes or no")
while travelling == "yes" :
      num = int(input("number of people"))
 for num in range( 1 , num+1):
     name = input("name")
     age = input("age")
     gender = input("gender")
     print(name)
     print(age)
     print(gender)
travelling = input("oops missed someone")

In this program we have used a while loop and inside the body of the while loop, we have incorporated a for loop.

The concepts discussed in this blog will help you understand the loops in Python. This will be very handy when you are looking to master Python and will help you make your code efficient. Python is a widely used high-level language.

Now that you have gone through the loops in python and their applications, you might want to check out the Python training by Edureka.

Have any queries? do not forget to mention them in the comments and we will get back to you.

Upcoming Batches For Python Programming Certification Course
Course NameDateDetails
Python Programming Certification Course

Class Starts on 28th December,2024

28th December

SAT&SUN (Weekend Batch)
View Details
Python Programming Certification Course

Class Starts on 25th January,2025

25th January

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Loops In Python: Why Should You Use One?

edureka.co