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
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))
+ 2
while i**2<=n:
if n==i**2:
return True
i += 1 # i = i+1
return False
+ 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
+ 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
+ 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