Financial Year 2023 End Sale: Get upto 40% OFF on Job-oriented Training! Offer Ending in
D
H
M
S
Get Now
Types of Loops in Python - For, While Loop

Types of Loops in Python - For, While Loop

06 Mar 2024
Beginner
2.86K Views
12 min read
Learn via Video Course & by Doing Hands-on Labs

Python Programming For Beginners Free Course

Python While, For, and Nested Loop: An Overview

With the help of the Python Tutorial and properly structured while, for, and nested loops, you’ll be able to stand out as a skilled coder by writing shorter, more efficient programs with fewer bugs. But when it comes to actually using these powerful statements, where do you start? If this is something that’s been puzzling you lately, then you might wanna consider enrolling in a Python Certification Course.

What is a loop in Python?

A loop is a control flow statement in Python that allows you to execute a piece of code repeatedly until a specific condition is met. Loops are necessary for operations that require repetitive execution, such as iterating through a Python list of items or doing calculations many times.

Read More - 50 Python Interview Questions and Answers

Different Types of Loops in Python

To understand the Loop Structures in Python, you need to know that there are 3 Types of Loops in Python, those are:

  1. Python while loop
  2. Python for loop
  3. Python nested loop

1. Python while loop

  • In Python, a while loop is a control flow statement that allows you to execute a block of code repeatedly while a given condition is true.
  • The condition is evaluated at the start of each loop iteration, and if it is true, the loop body is executed.
  • The loop is terminated if the condition is false.

Python while loop

Syntax of Python while loop

while expression:
 statement(s)

Example of Python while loop

        count = 0
while (count < 10):
 print ('The count is:', count)
 count = count + 1
print ("Good bye!")

A while loop is a control flow statement that allows you to repeatedly run a block of code as long as a given condition is true. The condition in this case is count 10. This signifies that the loop will keep running as long as the variable count is less than 10.

Output

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
The count is: 9
Good bye!

Read More - Python Developer Salary

2. Python for loop

  • A for loop is a control flow statement in Python that allows you to iterate over a sequence of elements such as a list, tuple, or string.
  • On each iteration, the loop variable in Python will take on the value of the next item in the sequence.

Python for loop

Syntax of Python for loop

for iterating_var in sequence:
 statements(s)

Example of Python for loop

        for letter in 'Python': # First Example
 print ('Current Letter :', letter)
fruits = ['guava', 'apple', 'mango']
for fruit in fruits: # Second Example
 print ('Current fruit :', fruit)
print ("Good bye!")

The code consists of up to two for loops that traverse over a Python string and a list in Python. The first loop loops through the string 'Python', printing the current letter to the terminal. The second loop iterates through the 'fruits' list, printing the current fruit to the terminal. Finally, the code outputs to the terminal the message "Goodbye!"

Output

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : guava
Current fruit : apple
Current fruit : mango
Good bye!

3. Python Nested loop

  • In Python, a nested loop is a loop that is contained within another loop.
  • This indicates that the inner loop is executed within each outer loop iteration.
  • Nested loops are handy for iterating over a two-dimensional array or processing hierarchical data.

Syntax for Nested for loop

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

Syntax for Nested while loop

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

Example of Python Nested Loop

        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
print ("Good bye!")

Using a nested while loop, this code snippet determines prime numbers between 2 and 100. The outer loop iterates through numbers ranging from 2 to 100, while the inner loop determines if each number is divisible by any number ranging from 2 to its square root. If a number in the inner loop is not divisible by any other number, it is considered prime and written to the console. The outer loop is repeated until it reaches 100, at which point "Goodbye!" is printed.

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
Good bye!

Loop Control Statements in Python

In Python, loop control statements are used to alter the regular flow of a loop. They enable you to skip iterations, end the loop early, or do nothing at all. Python's main three loop control statements are:
  1. Break
  2. Continue
  3. Pass

1. Break

The break statement is used to quickly stop the loop regardless of whether the loop condition is still true. This signifies that the loop will be terminated and the next statement outside of the loop will be executed.

Example of Break Statement in Python

          
for i in range(10):
  if i == 5:
    break
  print(i)
This code prints the numbers 0 to 4, but then it exits the loop and moves on to the next statement.

Output

0
1
2
3
4

2. Continue

The continue statement is used to skip the current loop iteration and go to the next iteration. This implies that the code from the current iteration will not be performed, and the loop will continue to iterate until the loop condition is satisfied.

Example of Continue Statement in Python

          
for i in range(10):
  if i % 2 == 0:
    continue
  print(i)
This code generates the odd numbers 1 through 9. Any iterations where the integer is even are skipped by the continue statement.

Output

1
3
5
7
9

3. Pass

The pass statement is a null statement that has no effect. It can be utilized as a placeholder in control statements or empty loops.

Example of Pass Statement in Python

        for i in range(10):
  # Do nothing
  pass
This code will not print anything because the pass statement does nothing. It is frequently used as a placeholder in control statements or empty loops.
Summary

In this article, we have learned about the different types of loop statements in Python. We have also seen how to use them with the help of examples. Whether you're a Python beginner or looking to enhance your skills, mastering these loop statements can greatly improve your coding abilities. So why not consider pursuing a Python certification to solidify your knowledge and showcase your expertise?

FAQs

Q1. What is a loop in Python?

Looping is the process of repeating something until a specific condition is met. In Python, a for loop is a control flow statement that is used to execute a series of instructions repeatedly as long as the condition is met. An iterative statement is another name for this type of statement.

Q2. What is a for loop in a Python flowchart?

Python loops are used to iterate across a set of statements, data structures, or iterable objects. The iterating variable is allocated to each item in the sequence, and then the set of statements is executed on it.

Q3. What is a loop string in Python?

Using for i in range(len(str)): is one technique to iterate over a string. The variable i receives the index in this loop, allowing each character to be accessed using str[i]. 
Share Article
About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Accept cookies & close this