0

Given an integral number, determine if it's a square number

I wrote this code below but it show error for no. 4 and 25 Error shown:- (4 is a square number: False should equal True 25 is a square number: False should equal True ) Couldn't understand why? code:- def is_square(n): i=1 if (n>0): while (i<=n): if (n%i==0): if (n==(i**2)): return True else: return False else: i=i+1 elif(n==0): return True else: return False

5th Sep 2019, 3:11 PM
Nik
Nik - avatar
5 Answers
+ 4
I found your logic a bit confusing and did a try like that: def is_sqlr(n): if n == 0: return False for i in range(1,n + 1): if i ** 2 == n: return True return False print(is_sqlr(25))
5th Sep 2019, 4:13 PM
Lothar
Lothar - avatar
+ 2
while i**2<=n: if n==i**2: return True i += 1 # i = i+1 return False
5th Sep 2019, 9:00 PM
Diego
Diego - avatar
+ 2
ive made it as identical to your code as possible def is_square(n): i=1 if (n>0): while (i<=n): if (n%i==0): if (n==(i**2)): return True i=i+1 return False elif(n==0): return True else: return False
6th Sep 2019, 4:53 PM
Choe
Choe - avatar
+ 1
I didn't check the rest of the code, but what you did wrong here is that you started from i=1, literally any number%1=0, so whatever number you try will give False, change i=1 to i=2
5th Sep 2019, 3:54 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 1
As Aymane Boukrouh pointed out, your only error is in the second line i=1. Replace it with i=2 and your code will work. Another approach using a simple generator (TWOLINER) https://code.sololearn.com/cFx04Symz9ly/?ref=app Or using a list comprehension and a ternary conditional operator (ONELINER) https://code.sololearn.com/cpb1l46tjwc2/?ref=app
6th Sep 2019, 1:37 PM
Bilbo Baggins
Bilbo Baggins - avatar