+ 1
What is the best way to determine the float number?
Hey, guys! What is the best way to determine if the entered number is a float type?
20 Antworten
+ 2
You can also look at isinstance()
https://www.w3schools.com/JUMP_LINK__&&__python__&&__JUMP_LINK/ref_func_isinstance.asp
but for user input, this might also require eval(), which I was trying to avoid.
Using this,
print(isinstance(39, float))
will return false, which is the behaviour you want.
+ 2
Guys, I extremely strongly did not want to use eval () on this tried to do at least something that can replace it! https://code.sololearn.com/cV7IlUXY7KiL/?ref=app - Is this another way to determine the float number?
+ 2
Сергей Серёгин
Actually, if you finally plan to use regex, we can completely skip the try catch statements, but remember to add word boundaries for a proper regex search.
https://code.sololearn.com/c0q4ovO558ll/?ref=app
+ 1
Hatsy Rei. This way doesnt work for me. Since when you enter a number of 3, the program thinks that the user has entered a number of float type
+ 1
Hatsy Rei Perfectly! But what to do with "3." and ".3"? I suggest we use regular expressions. Since I found no other way
https://code.sololearn.com/cdRcroAKOyiL/?ref=app good?
+ 1
the best solution and shortest:
My 4 lines snippet solution:
................
if input % 2 != 0:
return „float number“
else :
return „Int number“
...................
lol
0
You can try to convert it to float. If an exception is caught, the input isn't float.
try:
n = float(input())
# n is float
except ValueError:
# n is not float
0
My code can help you check if the input value contains a decimal point.
str=input()
if (str[0]=='-'):
str=str[1:]
if (str.isdigit()):
print('It is an integer.')
else:
print('It is a decimal or float number. ')
0
Giorganio -
1) Why do you wrap "input" in "str"
2) "isdigit" will show "False" at negative number
0
Сергей Серёгин 1) Actually,it is redundant as the input is already a string.
2) In order to make my code work for negative numbers,I have modified my code.
0
Cbr✔[ Most active ] I understand your concerns but "&#$@+%+" and alphabets are not something that will appear in a number so I think there will be no problem.
0
Сергей Серёгин If you wish, but even calculators accept 3. and .3 notations. I see it unnecessary, but no harm to go the extra mile.