0

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

Santi
  • 5
  • 3
  • 1
    `isinstance(number,int)` asks "is this value an `int`"? In your case, it is neither `int` nor `float`, it is a string. You can make a pretty good guess as to whether it can work as a float or not by doing `if number.find('.') >= 0:`. – Tim Roberts Apr 19 '21 at 22:42
  • In your code, `number = input('───→ ')` **will always be a `str` object**. Therefore, it will never be a `int` or `float` object. `isinstance("42", int)` is false... `isinstance("42", str)` is true... – juanpa.arrivillaga Apr 19 '21 at 22:48

1 Answers1

0

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

Jiří Baum
  • 6,697
  • 2
  • 17
  • 17
  • 1
    Yea, I was thinking about masking the final result instead, but modifying the validation function seemed more apropiate. Now that also see what you mean about "0.5 * 8 = 4", I think masking the result would be the better choise... I'll look up how to do that. Thank you very much! – Santi Apr 19 '21 at 23:04
  • Probably just munge the result after converting to string, really; `if result_text.endswith('.0'): result_text = result_text[:-2]` – Jiří Baum Apr 20 '21 at 00:20
  • Amazing results. Thank you! I clearly need to get deeper into string manipulation and string formating, so that was incredibly helpful. – Santi Apr 20 '21 at 00:45