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 Overflowpython - Identifying the data type of an input - Stack Overflow
python - How to check input type? - Stack Overflow
How do you determine what data type user inputs (python 3)?
How to detect user input type without breaking the program?
from ast import literal_eval
def get_type(input_data):
try:
return type(literal_eval(input_data))
except (ValueError, SyntaxError):
# A string, so return str
return str
print(get_type("1")) # <class 'int'>
print(get_type("1.2354")) # <class 'float'>
print(get_type("True")) # <class 'bool'>
print(get_type("abcd")) # <class 'str'>
input() will always return a string. If you want to see if it is possible to be converted to an integer, you should do:
try:
int_user_var = int(user_var)
except ValueError:
pass # this is not an integer
You could write a function like this:
def try_convert(s):
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
try:
return bool(s)
except ValueError:
return s
However, as mentioned in the other answers, using ast.literal_eval would be a more concise solution.
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...
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.
First of all numbers can also be strings. Strings are anything which is enclosed in double quotes. Anyway if all you need is to get an input and verify that it's not a number you can use:
inp = input("Input: ")
if inp.isdigit():
print("You must input a string")
else:
print("Input is a string")
Or if you wish to have a string with no digits in it the condition will go something like this:
inp = input("Input: ")
if any(char.isdigit() for char in inp) :
print("You must input a string")
else:
print("Input is a string")
It will always be a string as input() captures the text entered by the user as a string, even if it contains integers.
Wasn't able to find why you version isn't working (as documentation states it should work for type(...) is syntax, but in my case changing type to if isinstance(argv[0], int): removed your mypy error.
I recommend ensuring that _li is always type List[int].
I haven't tested the below code, but cast should work:
if isinstance(argv[0], int):
self._l1 = [cast(int, argv[0]), cast(int, argv[1]), cast(int, argv[2]), cast(int, argv[3]), cast(int, argv[4])]
else:
self._l1 = cast(List[int], argv[0])
print(type(self._li))
And where you declare _li and _myvar:
_li: List[int]
_myvar: List[int]
Assuming you're using python 3.X, everything the user inputs will be a string. Even numbery looking things like "23" or "0". int(thing) doesn't validate that thing is of the integer type. It attempts to convert thing from whatever type it is now, into the integer type, raising a ValueError if it's impossible.
Demonstration:
>>> while True:
... x = input("Enter something: ")
... print("You entered {}".format(x))
... print("That object's type is: {}".format(type(x)))
...
Enter something: hi
You entered hi
That object's type is: <class 'str'>
Enter something: hi46
You entered hi46
That object's type is: <class 'str'>
Enter something:
You entered
That object's type is: <class 'str'>
Enter something: ]%$
You entered ]%$
That object's type is: <class 'str'>
Enter something: 23
You entered 23
That object's type is: <class 'str'>
Enter something: 42
You entered 42
That object's type is: <class 'str'>
Enter something: 0
You entered 0
That object's type is: <class 'str'>
You can do this without relying on an exception using isdigit():
answer = input("Enter an integer: ")
while not answer.isdigit():
print("That's not a whole number. Try again.")
answer = input("Enter an integer: ")
answer = int(answer)
isdigit() tests to see if the input string is made up entirely of numbers that can be converted with int().