The "loop and a half"

Rhodri James rhodri at kynesim.co.uk
Tue Oct 3 13:45:02 EDT 2017


On 03/10/17 18:29, Stefan Ram wrote:
>    Is this the best way to write a "loop and a half" in Python?

Define "best".

> x = 1
> while x:
>      x = int( input( "Number (enter 0 to terminate)? " ))
>      if x:
>          print( f'Square = { x**2 }' )

I'd usually write it as

while True:
   x = tedious_function_call_with_sentinel()
   if x == 0:
     break
   do_something_with(x)

...or alternatively

x = tedious_function_call_with_sentinel()
while x != 0:
   do_something_with(x)
   x = tedious_function_call_with_sentinel()

...or some other refactoring.

>    In a C-like language, one could write:
> 
> while x = int( input( "Number (enter 0 to terminate)? " ))
>      print( f'Square = { x**2 }' )

One could.  One would richly deserve the compiler warnings one got as a 
result, but one could.

-- 
Rhodri James *-* Kynesim Ltd



More information about the Python-list mailing list