[Tutor] Python-list thread: int vs. float

boB Stepp robertvstepp at gmail.com
Sat Feb 11 16:28:19 EST 2017


On Sat, Feb 11, 2017 at 2:06 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Fri, Feb 10, 2017 at 07:59:04PM -0600, boB Stepp wrote:
>
>> He cannot figure out how to reliably tell if the user's input is an
>> integer, float or neither.  So I thought I would come up with my
>> solution, which currently is:
>>
>> py3: def ck_input():
>> ...     value_to_ck = input('Enter a number:')
>> ...     try:
>> ...             value = int(value_to_ck)
>> ...             print('You have entered an integer.')
>> ...     except ValueError:
>> ...             try:
>> ...                     value = float(value_to_ck)
>> ...                     print('You have entered a float.')
>> ...             except ValueError:
>> ...                     print('You have failed to enter a numerical value.')
>> ...

> The only not-so-good part of this is that you have mixed user-interface
> and internal calculation. Better:
>
>
> def to_number(string):
>     """Convert string to either an int or a float, or raise ValueError."""
>     try:
>         return int(string)
>     except ValueError:
>         return float(string)
>
>
> def check_input():
>     value_to_ck = input('Enter a number: ')
>     try:
>         value = to_number(value_to_ck)
>     except ValueError:
>         print('You have failed to enter a numerical value.')
>         return
>     if isinstance(value, float):
>         print('You have entered a float.')
>     else:
>         print('You have entered an int.')
>
>
> This gives you nice separation between the function that interacts with
> the user, and the function that does the actual conversion.

Ah!  I am glad I asked the questions.  There is a difference between
intellectually understanding what I should do and reliably
implementing it in my regular coding practice.  This is one such
instance, probably of many unfortunately.  I knew something was
bothering me about this.  I did not like nesting try...except
two-deep.  Now that you have shown the way, I see what was nagging at
me.  Thanks, Steve!

boB


More information about the Tutor mailing list