For vs while loop python

Yes, there is a huge difference between while and for.

The for statement iterates through a collection or iterable object or generator function.

The while statement simply loops until a condition is False.

It isn't preference. It's a question of what your data structures are.

Often, we represent the values we want to process as a range [an actual list], or xrange [which generates the values] [Edit: In Python 3, range is now a generator and behaves like the old xrange function. xrange has been removed from Python 3]. This gives us a data structure tailor-made for the for statement.

Generally, however, we have a ready-made collection: a set, tuple, list, map or even a string is already an iterable collection, so we simply use a for loop.

In a few cases, we might want some functional-programming processing done for us, in which case we can apply that transformation as part of iteration. The sorted and enumerate functions apply a transformation on an iterable that fits naturally with the for statement.

If you don't have a tidy data structure to iterate through, or you don't have a generator function that drives your processing, you must use while.

In this Python tutorial, we will discuss the For loop vs while loop in Python. Here we will also cover the below example:

  • What are loops
  • Loops in python
  • For loop in python
  • While loop in python
  • For loop vs while loop in Python

What are loops?

  • Loops basically allow us to terminate a statement or a group multiple times in a given condition.
  • In Python, there are many conditions defined in the beginning to enter the loop.
  • In Python, if the condition becomes false the loop stops and the condition will exit from the loop.

Read: Python While loop condition

Loops in Python

  • Now we will discuss how many types of loops are available in Python.
  • There are three types of loops one is for loop, while loop, and nested loop. So in this tutorial, we will discuss only for loop and while loop concept.

In Python, while loop is basically used to know how many iterations are required.

Here is the Flow chart of while-loop

Flow chart while loop

Syntax of while loop:

While condition:
    statement

In Python, you don’t know how many times you need to execute the statements that are present inside your body loop.

Let us check the while loop condition with the help of an example:

Source Code:

z = 7

while z < 12:
    print[z]
    z += 1

In the above code, we write this while loop condition z is less than 12 [x

Chủ Đề