-1

Hi im a complete beginner can anyone help me out why is my code not functioning?

-trying to whether the number is a square number (true / false)

import math 

def is_square(n): 

    if n >= 0:
        if math.sqrt (n).is_integer :
            print (n,"is a square number")
            return True
            
        else:
            print (n," is not a square number ")
            return False
          
    else: 
        print ( n,":","Negative numbers cannot be square numbers")
        return False
Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22
  • 1
    What is the exact error that you are getting? Is it not working for a particular input? If yes, what is the input? – tom Nov 28 '20 at 04:14
  • 2
    In your own words, what do you expect `math.sqrt (n).is_integer` to mean? – Karl Knechtel Nov 28 '20 at 04:25
  • You need to use `is_integer()` instead of `is_integer`. However, this will not solve the problem. – Joe Ferndz Nov 28 '20 at 04:58
  • Does this answer your question? [Python - Check if a number is a square](https://stackoverflow.com/questions/44531084/python-check-if-a-number-is-a-square) – Joe Ferndz Nov 28 '20 at 05:05
  • I understand my mistake abt math.sqrt returning a floating number but out of curiosity what is the difference between is_integer() instead of is_integer ? Thanks btw for taking time to comment – ILikeButter Nov 29 '20 at 10:08

2 Answers2

2

Syntax: variable. is_integer()

import math 

def is_square(n): 

    if n >= 0:
        if math.sqrt (n).is_integer() : # you need to call the .is_integer method
            print (n,"is a square number")
            return True
            
        else:
            print (n," is not a square number ")
            return False
          
    else: 
        print ( n,":","Negative numbers cannot be square numbers")
        return False
is_square(-4)
is_square(4)
is_square(5)
-4 : Negative numbers cannot be square numbers
4 is a square number
5  is not a square number 

To get better insight, try getting the output:

print(math.sqrt (5).is_integer(), '\n' ,math.sqrt (5).is_integer)
False 
 <built-in method is_integer of float object at 0x7f320fba2360>
Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22
1

math.sqrt (n) returns a float number. For example, math.sqrt(144) would give you 12.0. so, is.integer() method won't work. Try adding this piece of code:

if n >= 0:
        p=math.sqrt(n)
        if p==int(p):
            print (n,"is a square number")
            return True
        else:
            return False 
           

here are some examples:

>>> 12==int(12)
True
>>> 12.0==int(12.0)
True
>>> 12.3==int(12.3)
False
a121
  • 798
  • 4
  • 9
  • 20