How to use if condition inside a loop?

Question:

I want to solve a problem given by our teacher. The problem is: make a Python program that verifies if a number is a perfect square. If it’s a perfect square it, shows a message and if not it shows another message.

This is my attempt:

n = int(input('choose a number'))
for i in range(1,n):
    if n//i==i:
        d=i
print(n,'is a perfect square and its root is,',d)

During my attempt, I couldn’t add the else condition where the number is not a perfect square.

Asked By: saad elmoraghi

||

Answers:

you gave this a good go. Has your teacher taught you about importing modules yet? Basically, a module is like a Python file, and you can take functions from that file and use them in your file. One module is ‘math’ and holds a function called ‘sqrt’ that calculates the square root of a given number. If this square root is a whole number (has no remainder) the given number is square — is not, it’s not square. See the program I wrote below:

import math

num = int(input("Number = "))
square_root = math.sqrt(num)
if square_root % 1 == 0:
    print(f"It's square. {int(square_root)} squared gives {num}")
else:
    print("It's not square")
Answered By: Daniel Crompton

Using your range method and without importing math, you could have done this:

n = int(input('choose a number: '))
for i in range(1,n+1):
    if i**2 == n:   ## square the i and see if it equals n
        print(n,'is a perfect square and its root is:',i)
        break       ## stop here 
       
    else:
      if i == n:    ## when all the i's have been tried, give up
        print(n,'is not a perfect square')
        
Answered By: gerald
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.