简体   繁体   中英

Python won't import math module. It's fetching a file that isn't even there. What do I do?

# quadratic.py
# A program that computes the real roots fo a quadratic equation.
# Illustrates the use of the math library
# Note: This program crashes if the equation has no real roots

import math # math makes the library available

def main():
    print "This program finds the real solutions to a quadratic"
    print

    a, b, c = input("Please enter the coefficients (a, b, c): ")
    discRoot = math.sqrt(b * b - 4 * a * c)
    root1 = (-b +discRoot) / (2 * a)
    root2 = (-b +discRoot) / (2 * a)

    print
    print "The solutions are: ", root1 , root2 

main()

Her's the error I'm getting:

Macintosh-7:python andrewmetersky$ python quadratic.py
The answer to my homework question: what is i+x+j =
Traceback (most recent call last):
File "quadratic.py", line 6, in
import math # math makes the library available
File "/Users/andrewmetersky/Desktop/Programming/Python/math.py", line 5, in
NameError: name 'jp' is not defined

The problem is, math.py isn't even a file in that location. It was, but I deleted it because i figured Python was trying to fetch that and not the math module. There is a file called math.pyc in that location...is that the module? why won't it fetch that.

Thanks

PS- Also, how do I make that section i just pasted appear as code w/in stack overflow without having to press space 4x for each line.

You will need to delete the .pyc file as well. That's the compiled version of the original .py file and python will use that if it's in the path. It only gets updated (re-compiled) if the source (.py) file is exists and is newer.

When you import a local file for the first time, Python converts that file into bytecode and labels it .pyc .

在Python自己的数学模块之前,您可以找到位于/ user / andrewmetersky / Desktop / Programming / Python中的名为“ math.py”的文件,重命名该文件并删除匹配的.pyc文件,然后一切都会恢复正常。

math is a standard Python library so your code should work as is.

To confirm run:

$python

>>import math

See what you get.

It seems like you are masking math library with your own definition in local directory.

Delete anything local that looks like math.py or math.pyc and try again.

Run

python import“ /Users/andrewmetersky/Desktop/Programming/Python/math.py”重命名它,或将quadratic.py移动到另一个目录。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM