The "loop and a half"

Peter Otten __peter__ at web.de
Tue Oct 3 14:10:29 EDT 2017


Stefan Ram wrote:
> Is this the best way to write a "loop and a half" in Python?
>> x = 1
> while x:
> x = int( input( "Number (enter 0 to terminate)? " ))
> if x:
> print( f'Square = { x**2 }' )
>> In a C-like language, one could write:
>> while x = int( input( "Number (enter 0 to terminate)? " ))
> print( f'Square = { x**2 }' )

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
>>>


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /