The "loop and a half"
Larry Hudson
orgnut at yahoo.com
Tue Oct 3 22:17:49 EDT 2017
On 10/03/2017 10:29 AM, 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 }' )
>
This does not answer your question and is only somewhat related.
Here is a generic number input function that I wrote for my own (hobby-programmer) use. The
docstring explains it.
--------------------
def get_num(prmt, lo=None, hi=None, dflt=None, flt=False, abrt=False):
"""Get a number from the console
Parameters:
prmt: The prompt to be used with the input function, required.
lo: The minimum permissible value, or None if no minimum (the default)
hi: The maximum permissible value, or None if no maximum (the default)
dflt: Default value to return with empty input, None is no default value
flt: If True, accepts and returns floats
If False, accepts and returns integers (the default)
abrt: If True empty input aborts and returns None
If False (the default) empty input is handled as invalid data
Invalid input or out-of-range values are not accepted and a warning message
is displayed. It will then repeat the input prompt for a new value.
Note: If the dflt parameter is given, its data type is not checked and
could be anything, and could also be used as an abort signal.
"""
while True:
val = input(prmt).strip()
if not val:
if abrt:
return None
if dflt is not None:
return dflt
try:
num = float(val) if flt else int(val)
except ValueError:
print('Invalid input, try again')
continue
# We have a valid number here, check for in-range
if (lo is None or num >= lo) and (hi is None or num <= hi):
return num
print('Number is out of range')
------------------
FWIW, as to your question, my preference is for the pseudo-do loop using 'while True' with a
break as described in other answers here.
Using this function, your loop could be:
while True:
x = get_num('Number (enter ) to terminate: ')
if x == 0: # Or if not x:
break
print(f'Square = { x**2 }')
OR my preference: Use empty input to terminate by making the input and test:
x = get_num('Number (<Enter> to terminate: ', abrt=True)
if x is None:
break
--
-=- Larry -=-
More information about the Python-list
mailing list