[Tutor] Differences between while and for
Steven D'Aprano
steve at pearwood.info
Sat Jun 15 03:24:50 EDT 2019
On Sat, Jun 15, 2019 at 02:53:43PM +1000, mhysnm1964 at gmail.com wrote:
> All,
>
>
>
> In C, Perl and other languages. While only uses a conditional statement and
> for uses an iteration. In python while and for seems to be the same and I
> cannot see the difference.
Python ``while`` uses a conditional statement, and Python ``for`` uses
iteration. Python's ``for`` is like "foreach" in some other languages.
while condition: ...
for x in values: ...
> Python does not have an until (do while) where
> the test is done at the end of the loop. Permitting a once through the loop
> block. Am I correct or is there a difference and if so what is it?
Correct, there is no "do until" in Python.
> Why doesn't Python have an until statement?
Because Guido didn't want one :-)
Because it is unnecessary: any "do until" can be written as a regular
while loop, using a break:
# do...until with test at the end
while True:
do_something()
if test:
break
# "loop and a half"
# https://users.cs.duke.edu/~ola/patterns/plopd/loops.html#loop-and-a-half
while True:
do_something()
if test:
break
do_something_else()
--
Steven
More information about the Tutor
mailing list