1

I'm receiving this error and I'm not really sure why considering I've got the import math line there.

NameError: name 'sqrt' is not defined

import math
x = float(input())
y = float(input())
z = float(input())
print('{:.2f} {:.2f} {:.2f} {:.2f}'.format(pow(x, z), pow(x, pow(y, z)), abs(x - y), sqrt(pow(x, z))))

EDIT: I was able to resolve the problem by using math.sqrt but I'm not sure why it's needed when the pow and abs functions work.

Timus
  • 10,974
  • 5
  • 14
  • 28
  • Look up imports. Either use `from math import sqrt` or `math.sqrt(...)`. – Jan Jul 17 '21 at 06:43
  • You have imported ```math``` but you haven't used it. ```sqrt``` is a function in that module. It is ```math.sqrt()``` –  Jul 17 '21 at 06:43
  • 2
    as an aside sqrt is just `pow(x,0.5)` – Joran Beasley Jul 17 '21 at 06:44
  • Take a look at what functions are [builtins](https://docs.python.org/3.8/library/functions.html#built-in-funcs) (and realize that all other functions have to be either defined or imported). – Timus Jul 17 '21 at 14:01

2 Answers2

4

You have to import sqrt from math. Without importing sqrt you can't use it.
You can try this:

from math import sqrt

Or you can also do:

math.sqrt

pow() and abs() are predefined functions in python but sqrt is not predefined in python. Alternatively, you can use pow(N, 1/2) as it is equivalent to sqrt(N)

Prayson W. Daniel
  • 14,191
  • 4
  • 51
  • 57
imxitiz
  • 3,920
  • 3
  • 9
  • 33
  • 2
    I would not recommend `from [package] import *` as it pollutes the namespace. Image two package with the same name function but two different implementations, by importing `*` the later will overide the former. – Prayson W. Daniel Jul 17 '21 at 06:47
  • 1
    It is also debugging nightmare if we import things as `*`. – Prayson W. Daniel Jul 17 '21 at 06:52
1

You are currently importing the entire math library and not actually using the sqrt function. You can fix this like so:

import math
x = float(input())
y = float(input())
z = float(input())
print('{:.2f} {:.2f} {:.2f} {:.2f}'.format(pow(x, z), pow(x, pow(y, z)), abs(x - y), math.sqrt(pow(x, z))))
0x263A
  • 1,807
  • 9
  • 22