Python Forum

Full Version: Loop In Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello All, I am learning python and I want to know the difference between while loop, do while loop, and for loop? Can anyone tell me the difference with some basic examples?
How are you learning? Your learning materials should tell you the difference between them. Python doesn't have a do while loop.
Really, just do a quick google search. You'll find dozens of different sites with Python loops and examples.
In simple terms -
  • For loop usually specifies an item inside a list, tuple, dictionary etc.
  • While loop usually is used to carry out a process repeatedly until a given condition is satisfied
As for do while loop - well, python doesn't really have that
There are different types of loops available in python ie. For loop and While loop.

There is a another function range() to create a sequence that we can use with For Loop.
@theknowshare - promoting tutorial with python 2 examples and more over not PEP8 compatible is not advisable. Please, restrain from posting with sole purpose to promote your site.
I have found that good practice is to start with Python built-in help (help('for'), help('while'))

>>> help('while')
The "while" statement
*********************

The "while" statement is used for repeated execution as long as an
expression is true:

   while_stmt ::= "while" expression ":" suite
                  ["else" ":" suite]

This repeatedly tests the expression and, if it is true, executes the
first suite; if the expression is false (which may be the first time
it is tested) the suite of the "else" clause, if present, is executed
and the loop terminates.

A "break" statement executed in the first suite terminates the loop
without executing the "else" clause’s suite.  A "continue" statement
executed in the first suite skips the rest of the suite and goes back
to testing the expression.

Related help topics: break, continue, if, TRUTHVALUE
(END)
press q to exit help