Home > Software design >  How to get only integer or float input
How to get only integer or float input

Time:10-20

I am trying to make a calculator in python. However, I want the user to be able to input an integer or float. But not a string, how can I do that?

This is my current code, however, the if statement does not do the intended job.

def calculator():
     x = (input("Please enter a number: "))

     y = (input("Please enter a second number"))

     if x or y != int or float:

          print("Invalid input, please enter a number")
          x = input("Please enter a number: ")
          y = input("Now, please enter a second number: Press enter to leave blank: ")

CodePudding user response:

you could add int or float before the input... for example:

x = int(input("Please enter a number: "))

So if you entered a string, it would not accept it and result in a Traceback

CodePudding user response:

You input always be a string, even if someone type a number. To convert the input into a int or a float, use :

x = int(input("text"))
y = float(input("text"))

Note that you should verify the input if you only want numbers, like

def check_user_input(input):
    try:
        # Convert it into integer
        val = int(input)
        print("Input is an integer number. Number = ", val)
    except ValueError:
        try:
            # Convert it into float
            val = float(input)
            print("Input is a float  number. Number = ", val)
        except ValueError:
            print("No.. input is not a number. It's a string")


input1 = input("Enter your Age ")
check_user_input(input1)

input2 = input("Enter any number ")
check_user_input(input2)

input2 = input("Enter the last number ")
check_user_input(input2)

CodePudding user response:

You could try something like the following:


while True:
    try:
        x = input('Enter int or float:')

        if x.find('.') == -1:
            x = int(x)
            break
        else:
            x = float(x)
            break
    except ValueError:
        print('Something went wrong, try again.')

print(type(x))

You have a while loop in which the user input is parsed. If it contains a . the user entered a float otherwise an int, thus the parsing in the respective statements. If the format is incorrect, a ValueError is raised and excepted, printing that the user should try it again. The info could be updated to be more suggestive. However, if either conversion is successful, the while loop is left and the type is printed. The loop could also be left using KeyboradInterrupt Ctrl C.

  • Related