This should work

user_input = input("Enter something ")

try:
    val = int(user_input)
    print("Input is an integer")
except ValueError:
    try:
        val = float(user_input)
        print("Input is a float")
    except ValueError:
        print("It's a string")
Answer from CopyrightC on Stack Overflow
๐ŸŒ
Better Programming
betterprogramming.pub โ€บ how-you-make-sure-input-is-the-type-you-want-it-to-be-in-python-521f3565a66d
How You Make Sure input() Is the Type You Want It to Be in Python | by Martin Andersson Aaberge | Better Programming
January 31, 2020 - food_list = ['milk' , 'bread' , 'cheese'] print (f'Item Choices:') for index, item in enumerate(food_list): print(f'{index} : {item}')user_input = input('choose an item: ') print (f'user chose {food_list[user_input]}') You probably guessed it already. You canโ€™t use a string as an index to fetch the value stored in that list position. Even if the user types โ€œ1,โ€ itโ€™ll fail because the input is still stored as a string.
๐ŸŒ
PYnative
pynative.com โ€บ home โ€บ python โ€บ check user input is a number or string in python
Python Check User input is a Number or String | Accept Numbers as input
April 24, 2021 - number1 = input("Enter number and hit enter ") print("Printing type of input value") print("type of number ", type(number1))Code language: Python (python) Run ยท Output Enter number and hit enter 10 Printing type of input value type of number class 'str' As you can see, The output shows the type of a variable as a string (str). Solution: In such a situation, We need to convert user input explicitly to integer and float to check if itโ€™s a number.
Discussions

python - Identifying the data type of an input - Stack Overflow
I am trying to print the data type of a user input and produce a table like following: ABCDEFGH = String 1.09 = float 0 = int true = bool etc. I'm using Python 3.2.3 and I know I could use type() ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to check input type? - Stack Overflow
I initially wrote this: n = input('How many players? ') while type(n) != int or n More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 6, 2015
How do you determine what data type user inputs (python 3)?
Use try and except for valueError https://www.pythonforbeginners.com/error-handling/python-try-and-except More on reddit.com
๐ŸŒ r/learnpython
7
5
December 16, 2018
How to detect user input type without breaking the program?
If int can't parse the input, it'll throw an exception. Use try/except. Check if the input is only digits. Figure out how. More on reddit.com
๐ŸŒ r/learnpython
4
1
June 29, 2022
๐ŸŒ
Real Python
realpython.com โ€บ python-type-checking
Python Type Checking (Guide) โ€“ Real Python
January 7, 2019 - The following dummy examples demonstrate that Python has dynamic typing: ... >>> if False: ... 1 + "two" # This line never runs, so no TypeError is raised ... else: ... 1 + 2 ... 3 >>> 1 + "two" # Now this is type checked, and a TypeError is raised TypeError: unsupported operand type(s) for +: 'int' and 'str'
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how do you determine what data type user inputs (python 3)?
r/learnpython on Reddit: How do you determine what data type user inputs (python 3)?
December 16, 2018 -

I was trying to code a program where a user inputs an integer and see if the number is even or odd.

This part was not a problem, but I am struggling to create code that determines whether the user input is int, float, or str.

I know that user input is always in string, and if I wanted to change it to integer, I just have to put int(<user input>).

But what I want to do is to see if the user has typed something other than integer; I don't want the program to error out because the user types in a float or a string.

For example, if user enters "123.sedfv", I want the program to say it's a string and loop back it to make the user re-type an integer instead of the code shutting down due to input error.

Another example: If user types in a negative number, "-1293898434.", I want it to say "even".

Also, if the user types, for example, "five", "five.", "5." I want the code to convert it to integer instead of saying string/float or giving error.

My current code:

#checks if user input is even or odd

def evenodd(num):
if num % 2 == 0:
return "The number is even."
else:
return "The number is odd."
# user inputs a number and prints if its even or odd
while True:
print(evenodd(int(input("Enter an integer: "))))

I am a total noob and have no idea where to start with this...

Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to detect user input type without breaking the program?
r/learnpython on Reddit: How to detect user input type without breaking the program?
June 29, 2022 -

I'm trying to build a random number guessing program, and an issue I've come across is that the program only works if the user inputs a number. If they input a string, the program just errors out and breaks. My goal is to detect the type of data the user has inputted, and do one of two things: 1) if the user inputted an integer, proceed with the rest of the program, 2) if the user inputted any other data type, print an error message to the console and let the user re-enter their input. Here is the source code:

import random

start = 1
end = 10
number = random.randint(start, end)
attempts = 1

print("Guess the number between " + str(start) + " and " + str(end) + ".")
response = int(input())

while True:
    if response == number:
        print("Correct! You guessed the number in " + str(attempts) + " attempts.")
        break
    elif response > number:
        print("Guess lower!")
        attempts += 1
        response = int(input())
    elif response < number:
        print ("Guess higher!")
        attempts += 1
        response = int(input())

Thanks in advance.

๐ŸŒ
Berkeley
pythonnumericalmethods.studentorg.berkeley.edu โ€บ notebooks โ€บ chapter10.04-Type-Checking.html
Type Checking โ€” Python Numerical Methods
Try your function for erroneous input arguments to verify that they are checked. def my_adder(a, b, c): # type check if isinstance(a, float) and isinstance(b, float) and isinstance(c, float): pass else: raise(TypeError('Input arguments must be floats')) out = a + b + c return out
๐ŸŒ
TestDriven.io
testdriven.io โ€บ blog โ€บ python-type-checking
Python Type Checking | TestDriven.io
December 1, 2023 - That's where runtime type checkers come into play. One such tool is pydantic, which is used to validate data. It raises validation errors when the provided data does not match a type defined with a type hint. pydantic uses type casting to convert ...
๐ŸŒ
Streamlit
discuss.streamlit.io โ€บ using streamlit
Check the user input type using python and streamlit - Using Streamlit - Streamlit
October 22, 2021 - I want to check the user input if its numeric or string. The problem is that the if statement always take the user input as string even if the input is numeric its converted by default into a string. How to fix this problem ? all_columns = df.columns.tolist() st_input_update = st.number_input if is_numeric_dtype(all_columns) else st.text_input with col1_search: regular_search_term=st_input_update("Enter Search Term")
๐ŸŒ
CodeSpeedy
codespeedy.com โ€บ home โ€บ check if user input is a string or number in python
Multiple ways to check if user input is a string or number in Python
October 18, 2021 - We can check if user input is a string or number in Python by using these functions: isdigit(), isnumeric() and type(num).
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ input-validation-in-python
Input Validation in Python - GeeksforGeeks
3 weeks ago - import re while True: email = input("Enter email: ") pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$" if re.match(pattern, email): break else: print("Invalid email format") print(email) ... The regular expression checks the basic structure of an email address...
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ python-how-to-ensure-function-input-types-464439
How to ensure function input types | LabEx
Understanding type annotations, implementing input validation, and leveraging Python's type hinting capabilities enables writing safer, more efficient functions with enhanced type safety and runtime error prevention.
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Best practice for type checking and assert statement - Python Help - Discussions on Python.org
September 14, 2023 - Hi, I would like to learn the ideas and concepts around how to code and/or design Python programs in order to define type hints, check type of inputs and/or if the inputs do exist. For instance, image I need to define a function that takes a list of strings as inputs. def fun(input: list[str]): if input and isinstance(input, str): input = [input] assert isistance(input, list), "input should be a list" Now, is that example a best practice on how to define a function?
๐ŸŒ
Automate the Boring Stuff
automatetheboringstuff.com โ€บ 2e โ€บ chapter8
Chapter 8 โ€“ Input Validation
Input validation code checks that values entered by the user, such as text from the input() function, are formatted correctly. For example, if you want users to enter their ages, your code shouldnโ€™t accept nonsensical answers such as negative numbers (which are outside the range of acceptable ...