Use the type() built-in function:
>>> i = 123
>>> type(i)
<type 'int'>
>>> type(i) is int
True
>>> i = 123.456
>>> type(i)
<type 'float'>
>>> type(i) is float
True
To check if a variable is of a given type, use isinstance:
>>> i = 123
>>> isinstance(i, int)
True
>>> isinstance(i, (float, str, set, dict))
False
Note that Python doesn't have the same types as C/C++, which appears to be your question.
Answer from gregjor on Stack OverflowUse the type() built-in function:
>>> i = 123
>>> type(i)
<type 'int'>
>>> type(i) is int
True
>>> i = 123.456
>>> type(i)
<type 'float'>
>>> type(i) is float
True
To check if a variable is of a given type, use isinstance:
>>> i = 123
>>> isinstance(i, int)
True
>>> isinstance(i, (float, str, set, dict))
False
Note that Python doesn't have the same types as C/C++, which appears to be your question.
You may be looking for the type() built-in function.
See the examples below, but there's no "unsigned" type in Python just like Java.
Positive integer:
>>> v = 10
>>> type(v)
<type 'int'>
Large positive integer:
>>> v = 100000000000000
>>> type(v)
<type 'long'>
Negative integer:
>>> v = -10
>>> type(v)
<type 'int'>
Literal sequence of characters:
>>> v = 'hi'
>>> type(v)
<type 'str'>
Floating point number:
>>> v = 3.14159
>>> type(v)
<type 'float'>
What's the canonical way to check for type in Python? - Stack Overflow
How do you determine what data type user inputs (python 3)?
How does Python recognize data type of a variable?
Type Checking in Python: How to ...
How to Check if Type Is String in Python?
What is type code in Python?
What is type class in Python?
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...