Use isinstance.
Use with AI>>> x = 12
>>> isinstance(x, int)
True
>>> y = 12.0
>>> isinstance(y, float)
True
So:
Use with AI>>> if isinstance(x, int):
print('x is a int!')
x is a int!
In case of long integers, the above won't work. So you need to do:
Use with AI>>> x = 12L
>>> import numbers
>>> isinstance(x, numbers.Integral)
True
>>> isinstance(x, int)
False
Answer from user225312 on Stack OverflowUse isinstance.
Use with AI>>> x = 12
>>> isinstance(x, int)
True
>>> y = 12.0
>>> isinstance(y, float)
True
So:
Use with AI>>> if isinstance(x, int):
print('x is a int!')
x is a int!
In case of long integers, the above won't work. So you need to do:
Use with AI>>> x = 12L
>>> import numbers
>>> isinstance(x, numbers.Integral)
True
>>> isinstance(x, int)
False
I like @ninjagecko's answer the most.
This would also work:
for Python 2.x
Use with AIisinstance(n, (int, long, float))
Python 3.x doesn't have long
Use with AIisinstance(n, (int, float))
there is also type complex for complex numbers
How do I check if a number is a float number or whole number?
python - check if an input is a float - Stack Overflow
python - function that checks if a number is a float - Stack Overflow
Float and int in if else statment.
while True:
while True:
print("Enter a number")
num1 = input("")
if (num1.isfloat()):
break
else:
continue
while True:
print("Enter a second number")
num2 = input("")
if (num2.isfloat()):
break
else:
continue
For context. I'm writing a super simple, two number calculator. And i wanted to write a section where it tests for a float. So when you type in a number, for number 1 (the variable is called num1), python is suppose to check if it is a float or not. And if it it, it will continue the script if it is. And ask for the number again if its not. However, I'm struggling to find the right syntax to check for a float. isdigit and numeric work, but for some reason isfloat() does not work for me. What am I typing wrong, I'm quite new to programming.
Don't use recursion for this kind of looping. Remember that every recursive call uses more and more memory to save all the new local variables.
Also, your "wrong input" clause can never be hit -- you have already checked that the operator is one of the ones you support.
def calculate():
while True:
operator = input("What operator do you wanna use(*,/,+,-)? ")
possible_op = "+-*/"
if operator not in possible_op:
continue
try:
number_1 = float(input("What is your first number? "))
number_2 = float(input("What is your second number? "))
except ValueError:
continue
if operator == "+":
print(number_1 + number_2)
elif operator == "-":
print(number_1 - number_2)
elif operator == "*":
print(number_1 * number_2)
elif operator == "/":
print(number_1 / number_2)
break
Maybe this can help you, is a separated function that if the given number is float return True or False
def is_float(number):
if isinstance(number, float):
return True
else:
return False
You can call it in your code like this, you pass the number in this case number_1 as a parameter:
if is_float(number_1):
# do something
Sometimes it's better to ask for forgiveness than permission.
def get_float():
while True:
number = input('Input a number ')
try:
return float(number)
except ValueError:
print('\n bad input\n ')
number = input('Input a decimal number ')
while number != float:
This is wrong for a few reasons.
First, input() returns a string, so number is a string. It is not a floating point value.
Second, even if number were a proper floating point value, it is not equal to float, because float is a type object.
It seems like you really meant if type(number) != float. (But again, that would always be false here, because number is a string.)
Hi!
Im wondering how to check if a value is a float or int using an if else statement.
E.g
test = int(input("Add a random number!"))
value = test / 4
if ..............?
print("Hello")
else:
print("Hello2")
I have no idea if this is even close to being the right way to do it since i just started to learn Python and have no prior experience in programming.
Can someone please show me the way to do it since I can't find the answer on the internet!!
The easiest way is to convert the string to a float with float():
>>> float('42.666')
42.666
If it can't be converted to a float, you get a ValueError:
>>> float('Not a float')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'Not a float'
Using a try/except block is typically considered the best way to handle this:
try:
width = float(width)
except ValueError:
print('Width is not a number')
Note you can also use is_integer() on a float() to check if it's an integer:
>>> float('42.666').is_integer()
False
>>> float('42').is_integer()
True
def is_float(string):
try:
return float(string) and '.' in string # True if string is a number contains a dot
except ValueError: # String is not a number
return False
Output:
>> is_float('string')
>> False
>> is_float('2')
>> False
>> is_float('2.0')
>> True
>> is_float('2.5')
>> True
I would just use..
try:
float(element)
except ValueError:
print("Not a float")
..it's simple, and it works. Note that it will still throw OverflowError if element is e.g. 1<<1024.
Another option would be a regular expression:
import re
if re.match(r'^-?\d+(?:\.\d+)$', element) is None:
print("Not float")
Python3 method to check for float:
def is_float(element: any) -> bool:
#If you expect None to be passed:
if element is None:
return False
try:
float(element)
return True
except ValueError:
return False
Python2 version of the above: How do I parse a string to a float or int?
Always do unit testing. What is and is not a float may surprise you:
Command to parse Is it a float? Comment
-------------------------------------- --------------- ------------
print(isfloat("")) False
print(isfloat("1234567")) True
print(isfloat("1_2_3.4")) True 123.4, underscores ignored
print(isfloat("NaN")) True nan is also float
print(isfloat("123.456")) True
print(isfloat("123.E4")) True
print(isfloat(".1")) True
print(isfloat("6.523537535629999e-07")) True
print(isfloat("6e777777")) True This is same as Inf
print(isfloat("-iNF")) True
print(isfloat("1.797693e+308")) True
print(isfloat("infinity")) True
print(isfloat("1,234")) False
print(isfloat("NULL")) False case insensitive
print(isfloat("NaNananana BATMAN")) False
print(isfloat(",1")) False
print(isfloat("123.EE4")) False
print(isfloat("infinity and BEYOND")) False
print(isfloat("12.34.56")) False Two dots not allowed.
print(isfloat("#56")) False
print(isfloat("56%")) False
print(isfloat("0E0")) True
print(isfloat("x86E0")) False
print(isfloat("86-5")) False
print(isfloat("True")) False Boolean is not a float.
print(isfloat(True)) True Boolean is a float
print(isfloat("+1e1^5")) False
print(isfloat("+1e1")) True
print(isfloat("+1e1.3")) False
print(isfloat("+1.3P1")) False
print(isfloat("-+1")) False
print(isfloat("(1)")) False brackets not interpreted
Sinking exceptions like this is bad, because killing canaries is bad because the float method can fail for reasons other than user input. Do not be using code like this on life critical software. Also python has been changing its contract on what unicode strings can be promoted to float so expect this behavior of this code to change on major version updates.