The "loop and a half"
Terry Reedy
tjreedy at udel.edu
Tue Oct 3 18:07:17 EDT 2017
On 10/3/2017 2:10 PM, Peter Otten wrote:
> Stefan Ram wrote:
>
>> Is this the best way to write a "loop and a half" in Python?
[snip while loop]
> Use iter() and a for loop:
>
>>>> def input_int():
> ... return int(input("Enter number (0 to terminate): "))
> ...
>>>> for x in iter(input_int, 0):
> ... print(f"Square = { x**2 }")
> ...
> Enter number (0 to terminate): 1
> Square = 1
> Enter number (0 to terminate): 2
> Square = 4
> Enter number (0 to terminate): 0
I think this is the best answer. Using a for loop cleanly separates the
source of a sequence of objects from processing the objects. While loop
raret in Python as they are only needed for other patterns, such as
'while mutable object is not in the state we want: modify some more',
and the number of modifications needed is not necessarity known ahead of
time.
--
Terry Jan Reedy
More information about the Python-list
mailing list