Help to find the square root of a positive Python number

Asked

Viewed 75 times

-6

I am a beginner in Python and I am doing some exercises to learn more about this language. In one question, you were asked to create a program that asked for a number and returned the square root of it. And necessarily if that number were negative, an error message should be presented.

I managed to make the code work through the "Math" library, but when I asked for the number, my program responds with an "None", which I don’t know how to remove. Follow my code and, from now on, thank you:

n = int(input(print('Digite um número:')))
if n < 0:
   print('Número inválido.')
else:
   raiz = math.sqrt(n)
   print(f'A raiz quadrada de {n} é {raiz}')  ```

2 answers

1


You don’t need that "print" inside the input

n = int(input(print('Digite um número:')))

Follows below the correct way:

n = int(input('Digite um número:'))

The complete code, if you want:

import math

n = int(input('Digite um número:'))

if n < 0:
    print('Número inválido.')
else:
    raiz = math.sqrt(n)
    print(f'A raiz quadrada de {n} é {raiz}')

0

In this code there are two errors. The first refers to the function print in the code line of input() - you must remove it. And the second mistake was that you called the library Math without importing it previously - in this case, you need to import the library Math.

Something else, if you’re using python 3.8 or higher you can make the code more concise using the concepts of Assignment Expressions.

Well, that way we can implement the following code:

from math import sqrt

while (n := int(input('Digite um número inteiro: '))) < 0:
    print('Valor INVÁLIDO!')

print(f'A raiz quadrada de {n} é: {sqrt(n):.2f}')

Note that when we execute this code we receive the following message: Digite um número inteiro: . Right now we must enter an integer number and press Enter.

From this moment the block while verify whether the value assigned to the variable n is less than 0. Positive case - the value being in fact a negative number - the message will be displayed INVALID VALUE! and otherwise the square root of n will be calculated, then the value of n will be displayed, as well as the value of its root.

Note that we can also resolve this issue without having to import the Math library. To do this just write the square root operation in the code.

OBSERVING:

The square root of x is: x ** (1/2).

This way the code will stay:

while (n := int(input('Digite um número inteiro: '))) < 0:
    print('Valor INVÁLIDO!')

print(f'A raiz quadrada de {n} é: {n ** (1 / 2):.2f}')

Also note that not all squared is a perfect square. Therefore, not every square root will be integer. Therefore, I have implemented in both codes the rounding of the square root value to two decimal places.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.