1
def sqrt(number):
    number = root**2
    return root

def area_triangle(a, b, c):
    x = (a+b+c)/2
    result = x*(x-a)*(x-b)*(x-c)
    print (sqrt(result))

area_triangle(4,5,6)

This gives me a name error which "NameError: name 'root' is not defined"

I want to do this without math.sqrt orroot = number**(1/2) How can I solve this without using these two and why doesn't the same error occurs as "NameError: name 'number' is not defined" if I use the alternative?

3
  • 1
    well root is indeed not defined. should be root = number**2 or what ever you're trying to accomplish here.
    – WilomGfx
    Commented Jul 17, 2017 at 2:50
  • 3
    Why don't you want to use math.sqrt or one-half power? I see two main reasons to avoid that:when you need more precision than the 15-17 significant digits that math.sqrt and one-half power provide, or you are working with large integers and you want an exact answer for the integer part of the square root. The decimal module handles the first case, and for the second case you can do a web search to find such a function. Commented Jul 17, 2017 at 9:25
  • I'm trying to learn all different methods, I don't want to learn just one way and left others out. Commented Jul 18, 2017 at 12:24

1 Answer 1

6

Python is not an equation solver, like Wolfram Alpha. It is a language that executes the instructions you give it.

root = number**(1/2)

is an instruction. It says: take number, which already exists, and raise it to the 1/2 power; name the result root.

number = root**2

is also an instruction, but not the one you want. It says: take root, which should already exist, and raise it to the 2nd power; name the result number. But root actually doesn't already exist, so you get an error.

The two options you give are the most sensible ones for finding a square root - not sure why you want to avoid them. You could, of course, implement a square-root-finding algorithm yourself, but it's definitely much more straightforward to use the built-in solutions! A small change could be using number**(.5) or math.pow(number,1/2) (this is, of course, equivalent to your 1/2).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.