Python Loops

What is a Loop?

As we have already come across the concept of looping in Java and C the general definition was it is a set of instructions which are repeated until a condition is reached.

Now let us discuss more about the concept of looping in Python.

Why do we use loops in Python?

Loops in Python are provided to handle looping requirements. A loop generally come into play when a block of statements or code to be iterated. Loops minimize the number of lines to be repeated and increase the work efficiency.

Let us now discuss the types of loops we have in Python.

Python provides the user with two loops:

  1. For Loop
  2. While Loop

Now let us discuss about loops more clearly step by step.

For Loop:

A for loop in Python is used for iterating a sequence which may contain a list, tuple, dictionary, set, or a string).

A for loop in Python just not only function like a keyword but works like a iterator method as found in other object oriented programming languages.

Now let us understand the concept of for loop more clearly with an example:

Code:
company = ["apple", "meta", "instagram"]
for x in company:
print(x)
Here we are just trying to invoke some words to a variable and printing them.
//output

While Loop:

As we have seen in the case of Java while loop was used to iterate a block of statements or code until the condition specified is true. It is the same scenario in the case of Python too while loop is used to iterate a block of statements until the condition specified is true.

Now let us understand the concept of while loop with an example:

Code:
i = 1
while i < 7:
    print(i)
    i += 2

This comes to end of the concept of introduction to looping in Python and also to this blog.

Follow us on our social platforms for more interesting content and do share it with your friends.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top