0

I have read some other questions from stackoverflow, all they need to do it change file name to something else, but my file name is different already:

import random

x = random.random()

print(x)

and I got error like:

Traceback (most recent call last):
  File "math.py", line 1, in <module>
    import random
  File "/anaconda3/lib/python3.6/random.py", line 42, in <module>
    from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
  File "/Users/pgao/Documents/Python Project/math.py", line 3, in <module>
    x = random.random()
AttributeError: module 'random' has no attribute 'random'

please help me with this simply question, i am selfstudy python language recently. thanks.

2
  • Try doing random.uniform(0,1) maybe. This will give a random float between 0 and 1. Or random.randint(lower, higher) where lower and higher are integers for a random integer. Commented May 6, 2020 at 6:48
  • Your file is named math.py, and it gets imported instead of the math module of the standard library. Rename it, and don't use names of standard modules for any of your files. Commented May 6, 2020 at 6:50

2 Answers 2

4

The problem is that the random module imports the math module, and since you named your own source file math.py it's what will be imported.

Rename your source file to something else.

Sign up to request clarification or add additional context in comments.

Comments

2

On the contrary, you've managed to shoot yourself in the foot by naming your file not random.py but math.py, which is also a builtin, and which random imports.

The traceback is exactly correct (thanks for including it!). When random tries to figure out what it is defined as, it imports math, which resolves to your original file. Your original file then tries to figure out what it is (again), but there is a placeholder for random (only 42 lines are evaluated so far), and it doesn't have any random.random attribute.

1 Comment

Hi thanks for the full explanation, it helps a lot for my dummy mistake. it works. appreciate it.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.