I am writing a program that needs to check if a users input is a decimal (the users input must be a deciamal number),I was wondering how I could test a varible to see if it contains only a decimal number.
Thanks, Jarvey
I am writing a program that needs to check if a users input is a decimal (the users input must be a deciamal number),I was wondering how I could test a varible to see if it contains only a decimal number.
Thanks, Jarvey
U also could use a Try/Except to check if the variable is an integer:
try:
val = int(userInput)
except ValueError:
print("That's not an int!")
or a float:
try:
val = float(userInput)
except ValueError:
print("That's not an float!")
You can use float.is_integer() method.
Example:
data = float(input("Input number"))
if data.is_integer():
print (str(int(data)) + ' is an integer')
else:
print (str(data) + ' is not an integer')
I found a way of doing this in python but it doesn't work in a new window/file.
>>> variable=5.5
>>> isinstance(variable, float)
True
>>> variable=5
>>> isinstance(variable, float)
False
I hope this helped.
You can use isinstance
:
if isinstance(var, float):
...
You can check it by converting to int:
try:
val = int(userInput)
except ValueError:
print("That's not an int!")
(one) fast anwer
a=1
b=1.2
c=1.0
d="hello"
l=[a,b,c,d]
for i in l:
if type(i) is float:
print(i)
#result : 1.0, 1.2
long answer : What's the canonical way to check for type in python?