If your inputs are "sometimes" ints and "sometimes" floats then just wrap each input in a float(). You could make something more complex, but why would you?

Answer from CambridgeCro on Stack Overflow
🌐
Smash Your Exams
code.smashyourexams.com › learn › learn python › input and data types › real and float input
Python float(input()) | int vs float at GCSE
Ask the user for a price, a height or a weight and you need a different cast: float(). float is Python's name for a real number, which is one that can have a decimal part. ... It works exactly like int(), and you read it the same way, from the ...
Discussions

Int or float of an input function in Python - Stack Overflow
While taking an Intro to Python course through Plural Sight, I found that the code that worked for me was different than that of the instructor. (Different version?) There is one difference I do not More on stackoverflow.com
🌐 stackoverflow.com
How to make python accept both int and float input???
It's very simple all you need to do is use float before asking to input the data i.e. int_float=float(input ("Enter the value:")) Suppose user inputs 45.9 or 3 both can be accepted using float More on sololearn.com
🌐 sololearn.com
161
66
How to accept only integer or float inputs?

I don't understand why you don't just use floats?

while True:
            try:
                time = float(raw_input("How much time has elapsed since your last stop (in hours)?"))
            except ValueError:
                print("Enter a valid number of hours!")
                continue

By typing an integer value, it'll just turn it into a float anyway.

More on reddit.com
🌐 r/learnpython
14
5
February 23, 2016
python 3.x - How to check if input is float or int? - Stack Overflow
The return type of input in Python3 is always str. Checking it against type(2.2) (aka float) and type(2) (aka int) thus cannot succeed. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Snakify
snakify.org › integer and float numbers
Integer and float numbers - Learn Python 3 - Snakify
When we read an integer value, we read a line with input() and then cast a string to integer using int(). When we read a floating-point number, we need to cast the string to float using float(): ... Floats with very big or very small absolute ...
Top answer
1 of 4
1

input returns a string:

>>> x = input()
5.0
>>> x
'5.0'

If this string contains a representation of a number and you want to use it as a number, you need to call an appropriate function to parse the string and determine what number it represents:

>>> float(x)
5.0

However if the string doesn't represent a number, or if it doesn't represent a number of the type you're trying to convert it to, you will get an error:

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

(Technically 5.0 is an integer, but typically we think of '5.0' as representing not the number 5.0 itself but as representing some unknown number which would round to 5.0, i.e. some number between 4.95 and 5.05. Hence the failure to convert to an integer.)

And of course if the string doesn't represent a number at all, all of this is right out.

>>> float('banana')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'banana'

EDIT: 0x5453 raises a good point in the comments, which is that prior to python 3 the language would do these string-to-number conversions implicitly in some cases, which may be what you're remembering.

2 of 4
1

The function input() gets text from the user as a string, the float() function is used to convert strings to float values. In the inputs you specified any value containing a comma will cause float() to throw an error since float() does not know what to do with the comma. The function does know how to convert numbers containing decimals though so those numbers will be fine. If you wanted to take input that contains commas you would have to sanitize your input like so:

float(input("How much money do you own, in dollars?\n").replace(',','')) # 50,000 
🌐
Medium
medium.com › @bawe97 › python-program-which-accepts-user-input-as-integer-or-float-a174f281e82f
Python program which accepts user input as integer or float | by Awe Oluwabambi | Medium
March 17, 2020 - Python normally sees any user input as a string, but we want to ensure that we get a product if the values are numbers. So, the next step is to call our multiply function such that we don’t get any error when the user enters a string, integer or floating point number.
🌐
IncludeHelp
includehelp.com › python › read-input-as-a-float.aspx
Read input as a float in Python
April 20, 2025 - There is no such method, that can be used to take input as a float directly – but input string can be converted into a float by using float() function which accepts a string or a number and returns a float value. Thus, we use input() function to read input and convert it into a float using ...
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › how to accept only integer or float inputs?
r/learnpython on Reddit: How to accept only integer or float inputs?
February 23, 2016 -

My current code accepts integers that are greater than 0, which is what I want, but I also want to accept floats/decimals as well. How would I do this? Here is my current code:

while True:
            try:
                time = int(input("How much time has elapsed since your last stop (in hours)?"))
            except ValueError:
                print("Enter a valid number of hours!")
                continue
            if time > 0:
                givenTime[2] = time
                break

Indentation is off here for some reason, but believe me when I say that the indentation in the actual code is correct..

Can I just do time = int or float(input("How much time has elapsed since your last stop (in hours)?")) or would this be wrong? Any help would be appreciated.

edit: nope,

time = int or float(input("How much time has elapsed since your last stop (in hours)?"))

doesn't work.

🌐
GeeksforGeeks
geeksforgeeks.org › python › check-if-value-is-int-or-float-in-python
Check If Value Is Int or Float in Python - GeeksforGeeks
July 1, 2025 - It returns True or False. ... a = 654 b = 566.8 print(isinstance(a, int)) print(isinstance(a, float)) print(isinstance(b, int)) print(isinstance(b, float)) ... Explanation: Here, we check each variable a and b against both int and float. a is correctly identified as an integer and b as a float. isdigit() method is used to check if all characters in a string are digits. It's commonly used for string inputs.
Top answer
1 of 4
3

TLDR: Convert your input using ast.literal_eval first.


The return type of input in Python3 is always str. Checking it against type(2.2) (aka float) and type(2) (aka int) thus cannot succeed.

>>> number = input()
3
>>> number, type(number)
('3', <class 'str'>)

The simplest approach is to explicitly ask Python to convert your input. ast.literal_eval allows for save conversion to Python's basic data types. It automatically parses int and float literals to the correct type.

>>> import ast
>>> number = ast.literal_eval(input())
3
>>> number, type(number)
(3, <class 'int'>)

In your original code, apply ast.literal_eval to the user input. Then your type checks can succeed:

import ast

number = ast.literal_eval(input("Please input your number...... \n"))
if type(number) is float:
    print("Entered number is float and it's hexadecimal number is:", float.hex(number)) 
elif type(number) is int:
    print("Entered number is, ", number,"and it's hexadecimal number is:", hex(number)) 
else:
    print("you entered an invalid type")

Eagerly attempting to convert the input also means that your program might receive input that is not valid, as far as the converter is concerned. In this case, instead of getting some value of another type, an exception will be raised. Use try-except to respond to this case:

import ast

try:
    number = ast.literal_eval(input("Please input your number...... \n"))
except Exception as err:
    print("Your input cannot be parsed:", err)
else:
    if type(number) is float:
        print("Entered number is float and it's hexadecimal number is:", float.hex(number)) 
    elif type(number) is int:
        print("Entered number is, ", number, "and it's hexadecimal number is:", hex(number)) 
    else:
        print("you entered an invalid type")
2 of 4
2

input returns a string, you are trying to check whether it looks like a float or an integer:

number = input("Enter your number? ")
try:
    number = int(number)
    print("Entered number is, ", number,"and it's hexadecimal number is:", hex(number))
except ValueError:
    try:
        number = float(number)
        print("Entered number is float and it's hexadecimal number is:", float.hex(number)) 
    except ValueError:
        print("You entered an invalid number")
🌐
Stack Overflow
stackoverflow.com › questions › 47651841 › input-as-float-or-int
python - input as float or int - Stack Overflow
Sign up to request clarification or add additional context in comments. ... N. Bartos Over a year ago · thanks! For some reason I thought float(input()) wouldn't accept an interger :/ 2017-12-06T06:32:47.147Z+00:00 ... Save this answer. ... Show activity on this post. ... spam = input('choose any number: ') try: print('Your number doubled is: ' ,int(spam)*2) except ValueError: print('Your number doubled is: ' ,float(spam)*2)
🌐
Quora
quora.com › How-can-I-check-whether-or-not-a-user-input-in-Python-is-a-float-or-an-integer-without-using-try-error-checking
How to check whether or not a user input in Python is a float or an integer without using try error checking - Quora
Answer (1 of 9): I would try to answer a more fundamental question first: What is the canonical source of truth regarding what is and isn't a float or an integer in the context of what you are trying to do? This depends on the specification or requirements you are working with. Random strangers ...
🌐
Davrot
davrot.github.io › pytutorial › python_basics › input_output_string_int_float
input, print, string, int, float
Otherwise, if the argument is an integer or a floating point number, a floating point number with the same value (within Python’s floating point precision) is returned.
🌐
TechNetExperts
technetexperts.com › home › [resolved] python int vs float: why not always use float
[Resolved] Python Int vs Float: Why Not Always Use Float
May 23, 2026 - Floats must strictly be reserved for continuous measurements, weights, geometric calculations, or scientific approximations. Instead of preemptively declaring a variable as a float, systems should enforce strict data validation at the boundaries (e.g., when an API payload is received). If an endpoint expects an integer but receives a string with a decimal (like “5.0”), the application should carefully sanitize and cast the input.
🌐
YouTube
youtube.com › watch
Input in Python - The Input() Function with Float() | How to take only Float Input in Python - YouTube
Input in Python - The Input() Function with Float() | input function in python | Float() function | How to take only Float Input in PythonSimilar to the inte...
Published: October 20, 2024
🌐
Hyperskill
hyperskill.org › university › python › input-and-input-in-python
Python input() Function: Get User Input with Examples
June 5, 2026 - By making use of type casting functions like float() int() or str() we can smoothly transform user input into different data types, in Python.
🌐
Reddit
reddit.com › r/learnpython › float and int function
r/learnpython on Reddit: Float and int function
March 25, 2023 -

Hello, please can someone explain to me when to use the float and int functions?

I mean should I use float when I am strictly dealing with decimal numbers, or when I want to convert whole numbers to decimal numbers?

pythonlearner

Top answer
1 of 4
5
float() and int() are mainly use to convert strings to numbers. They actually create a number from the strings. int() is also often use to create an integer number from a float number. A classic example is when you ask the user for a number. The input function always returns a string of character. To perform calculation you need a number (int or float). So you must create a number from that string. As in: string_number = input("Enter temperature in °F (integer): ") temp_far = int(string_number) temp_cel = (temp_far-32) * (5/9) # the result here is a float print("Temperature in celsius (float)", temp_cel) temp_cel_int = int(temp_cel) # creates an integer number from the float print("Temperature in Celsius (integer)", temp_cel_int) Using float on strings from math import radians angle_string = input("Enter a precise angle in degrees with decimal: ") angle_float = float(angle_string) radians_float = radians(angle_float) print("That angle in degrees is",radians_float,"in radians")
2 of 4
1
For string conversion, use the one appropriate to the string you're trying to convert. If you care about exact equality, don't use floats. Use integers, or maybe the Decimal class. If you want to know if floats are equal ish, keep in mind that the ish is always there. Use something like math.isclose to make such checks. There is rarely (almost never?) any need to explicitly convert integers to floats (unless you're doing something with numpy or similar). Integers will be automatically treated as floats during division (NOTE: different in some other languages), multiplication, etc. If you want to convert a float to integer, you can do that via int(2.3), but keep in mind how it rounds. There are other rounding functions that may or may not be more helpful (math.ceil, math.floor, round).
🌐
Kansas State University
textbooks.cs.ksu.edu › intro-python › 03-strings-input › 02-number-input
Numerical Input :: Introduction to Python
July 30, 2026 - Resources Slides Of course, we can also read numerical input in Python using the input() function. To do this, we must simply use either the int() or float() function to convert the input received as a string to the correct data type. Here’s a quick example program that requires two inputs ...