0

I'm making a calculator in python 3 and I'm wondering if there is an option that can tell if the input the user gave is not a float. For example if the user wrote a word instead of a float the code will recognize it and print out something like:

if num1 != float:
    print("You Need To Enter A Number")
Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50

2 Answers2

0

input() returns everything in str type. You need to manually test by conversion

def is_float(number):
    try:
        float(number)
        return True
    except ValueError:
        return False

number = input()
print(is_float(number))
tbhaxor
  • 1,659
  • 2
  • 13
  • 43
0

I'd just keep it simple. If it contains a dot, say it's a float.

number = input('Number: ')

if '.' in number:
    try:
        value = float(number)
        # Number is a float.
    except ValueError:
        print('Invalid input')
else:
    try:
        value = int(number)
        # Number is an integer.
    except ValueError:
        print('Invalid input')

Although, the best way is probably to use ast.literal_eval as explained in this answer.

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50