I have been following the thread "int vs. float"
(https://mail.python.org/pipermail/python-list/2017-February/719287.html)
on the main list.  A search for the OP on the Tutor archive came up
negative, so I am hoping he is not following Tutor tonight (Or anytime
prior to the due date for his homework!).  The central part of
adam14711993's question is:

"What I cannot figure out is how to write it so that if my user input
is, for example, 1.5, the program will result with: Sorry, you can
only order whole packages.

"I understand that because I am starting out by assigning my
number_purchases_str to be an int, when the user enters a float that
is a conflict and will crash."

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.')
...

(Yes, I know I am not doing anything with the variable, "value", but
if I were to actually implement this in the future, I am sure I would
find a use for it.  So I left it as is for the moment.)

My quick checks are:

py3: ck_input()
Enter a number:5
You have entered an integer.
py3: ck_input()
Enter a number:5.0
You have entered a float.
py3: ck_input()
Enter a number:'5'
You have failed to enter a numerical value.

This is all well and good.  I am not trying to elicit an "Atta boy,
boB!" here. ~(:>)) Instead, I am wondering if there is something in
Python's wonderful cornucopia of programming stuff that can simplify
this type of check.  As you might guess from my earlier post this
evening, I have been playing around with "type()" and "isinstance()",
but if I try something like:

py3: isinstance(int('5.0'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'

I get the ValueError I make use of in my function above.

So, is there any easier way to do this check?  If not, can my function
be improved to make it a bit less lengthy, but still eminently
readable?

TIA!
-- 
boB
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to