How Can I Put Type() With If Statement In Python?
I have TypeError: a float is required when I try putting type() with if statement example: from math import * x=input('Enter a Number: ') if type (sqrt(x)) == int: print (sqrt(
Solution 1:
there are 2 problems here :
1st
x=input("Enter a Number: ")
will be a string, not a number, using int(x)
should fix this
2nd
if type (sqrt(x)) == int:
sqrt()
always return a float, you can use float.is_integer()
, like this : sqrt(x)).is_integer()
to check if the square root is a integer.
final code :
from math import *
x=int(input("Enter a Number: "))
if sqrt(x).is_integer():
print (sqrt(x))
else:
print("There is no integer square root")
Solution 2:
You have to convert your input string to float before passing it to sqrt(). As far as Python is concerned, sqrt("5.4")
makes no more sense than sqrt("Bob")
. And x=float(x)
is a fine way to do that conversion.
There's no question of types here: input()
will always be string, and sqrt()
will always be float (never int).
Solution 3:
It seems that instead of an int, you just want a whole number. To check if something is a whole number, do a modulus division by 1.
from math import *
x = float(input("Enter a Number: "))
if sqrt(x) % 1 == 0:
print(sqrt(x))
else:
print("There is no integer square root")
Post a Comment for "How Can I Put Type() With If Statement In Python?"