0

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(x))
else:
    print("There is no integer square root")

obviously I can't use x= float(x)

6
  • 4
    “obviously I can’t use x= float(x)” – why not? Commented Apr 10, 2015 at 17:57
  • 1
    Use the float.is_integer method to test if a float is an int. Commented Apr 10, 2015 at 17:57
  • You can also use isinstance. Commented Apr 10, 2015 at 17:58
  • 1
    There's no question of types here. input returns a string, period. You need to convert that to a float (x = float(x) will work just fine) before passing it to sqrt(). Commented Apr 10, 2015 at 18:00
  • I image you are getting the error TypeError: a float is required. That's because x is a string. You can't take a square root of a string. Do note that even if you do sqrt(float(x)) your if-statement will never evaluate to true because math.sqrt always returns a float. Commented Apr 10, 2015 at 18:01

3 Answers 3

3

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")
Sign up to request clarification or add additional context in comments.

1 Comment

I suggest sqrt(x).is_integer() rather than float.is_integer(sqrt(x)). There's no need for the unbound method here.
1

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).

Comments

0

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")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.