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
python - check if an input is a float - Stack Overflow
python - How do I check if a string represents a number (float or int)? - Stack Overflow
python - How to check if a user input 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
User helper function:
Use with AIdef if_ok(fn, string):
try:
return fn(string)
except Exception as e:
return None
then
Use with AIif_ok(int, my_str) or if_ok(float, my_str) or if_ok(complex, my_str)
is_number = lambda s: any([if_ok(fn, s) for fn in (int, float, complex)])
Use with AIdef is_float(s):
if s is None:
return False
if len(s) == 0:
return False
digits_count = 0
dots_count = 0
signs_count = 0
for c in s:
if '0' <= c <= '9':
digits_count += 1
elif c == '.':
dots_count += 1
elif c == '-' or c == '+':
signs_count += 1
else:
return False
if digits_count == 0:
return False
if dots_count > 1:
return False
if signs_count > 1:
return False
return True
isinstance(next, (float, int)) will do the trick simply if next is already converted from a string. It isn't in this case. As such you would have to use re to do the conversion if you want to avoid using try..except.
I would recommend using the try..except block that you had before instead of a if..else block, but putting more of the code inside, as shown below.
def gold_room():
while True:
print "This room is full of gold. What percent of it do you take?"
try:
how_much = float(raw_input("> "))
if how_much <= 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
except ValueError:
print "Man, learn to type a number."
This will try to cast it as a float and if it fails will raise a ValueError that will be caught. To learn more, see the Python Tutorial on it.
RE would be a good choice
>>> re.match("^\d+.\d+$","10")
>>> re.match("^\d+.\d+$","1.00001")
<_sre.SRE_Match object at 0x0000000002C56370>
If the raw input is a float number, it will return an object. Otherwise, it will return None. In case you need to recognize the int, you could:
>>> re.match("^[1-9]\d*$","10")
<_sre.SRE_Match object at 0x0000000002C56308>
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!!
To check if a float value is a whole number, use the float.is_integer() method:
>>> (1.0).is_integer()
True
>>> (1.555).is_integer()
False
The method was added to the float type in Python 2.6.
Take into account that in Python 2, 1/3 is 0 (floor division for integer operands!), and that floating point arithmetic can be imprecise (a float is an approximation using binary fractions, not a precise real number). But adjusting your loop a little this gives:
>>> for n in range(12000, -1, -1):
... if (n ** (1.0/3)).is_integer():
... print n
...
27
8
1
0
which means that anything over 3 cubed, (including 10648) was missed out due to the aforementioned imprecision:
>>> (4**3) ** (1.0/3)
3.9999999999999996
>>> 10648 ** (1.0/3)
21.999999999999996
You'd have to check for numbers close to the whole number instead, or not use float() to find your number. Like rounding down the cube root of 12000:
>>> int(12000 ** (1.0/3))
22
>>> 22 ** 3
10648
If you are using Python 3.5 or newer, you can use the math.isclose() function to see if a floating point value is within a configurable margin:
>>> from math import isclose
>>> isclose((4**3) ** (1.0/3), 4)
True
>>> isclose(10648 ** (1.0/3), 22)
True
For older versions, the naive implementation of that function (skipping error checking and ignoring infinity and NaN) as mentioned in PEP485:
def isclose(a, b, rel_tol=1e-9, abs_tol=0.0):
return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
We can use the modulo (%) operator. This tells us how many remainders we have when we divide x by y - expresses as x % y. Every whole number must divide by 1, so if there is a remainder, it must not be a whole number.
This function will return a boolean, True or False, depending on whether n is a whole number.
def is_whole(n):
return n % 1 == 0