I'm making a very basic calculator as my first project (I'm learning Python and want something to show what i've learned so far) and as it is right now, the program works fine.
As it is right now, I have a function to validate user inputs so that the code only accepts numbers and decimal points, and returns the input as a float value to be calculated.
However, I would like to make it so that the code can recognize if the user is entering an Integer or a Float value, so that a simple operation such as "2+2" doesn't return a float "4.0" result, and just a "4".
The function that I have working right now is the following:
def valid_num():
number = ''
valid = True
while valid:
try:
number = float(input('───→ '))
break
except ValueError:
print('')
print('Invalid input (numbers and decimal points only).')
return number
To be able to diferentiate between integers and float values, I looked up methods and found the isinstance() function, which I may not be applying correctly... This is the function that I'm trying to make work:
def valid_num():
number = ''
valid = True
while valid:
number = input('───→ ')
check_int = isinstance(number, int)
if check_int:
number = int(number)
break
check_float = isinstance(number, float)
if check_float:
number = float(number)
break
if not check_int and not check_float:
print('Invalid input (numbers and decimal points only).')
return number
Sorry if there's an obvious error I'm not seeing, I'm just starting to code... Thanks in advance for any help you can provide =D
As pointed out by @tim-roberts, isinstance(number, int)
checks the type of number
, which is a string.
To distinguish ints and floats, you have a couple of options:
Try to convert it to int
, if that fails try to convert to float
; this would use a pair of try
/except
clauses.
Validate the input as text, checking that it follows the rules you set for your calculator, probably using regular expressions; this would let you positively assert that it matches what you expect, rather than whatever the int
and float
functions accept.
You could also work throughout in float
(or Decimal
), then convert 4.0
to 4
on output; that would mean that you'd also get "4" for "0.5 * 8" (which may be better or worse than getting "4.0"; that's up to your UX design).