2

It does not load the specific module of random when you run it as a .py. But if I load it in the python shell, I have no problems.

# -*- coding: utf-8 -*-
#!/usr/bin/env python

import random
print(random.randint(0,9))

I run it... and:

Traceback (most recent call last):
  File "random.py", line 4, in <module>
    import random
  File "C:\Users\root\Pythin\random.py", line 5, in <module>
    print(random.randint(0,9))
AttributeError: module 'random' has no attribute 'randint'

And in the python shell I have no problem:

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> print(random.randint(0,9))
1

I,m running it in Windows PowerShell (Windows10|64bits). Using the command python random.py. Someone gives me a hand? Thank you very much.

1
  • If you name your archive.py in the same way that Pyhton modules it does not work. Commented Apr 29, 2020 at 19:13

3 Answers 3

5

Change the file name of your code to "myrandom.py". And then run the program.

Update: Please don't name your Python source code file to standard modules. As it will cause error. Because right now instead of importing the standard library RANDOM of python, the python imports this random.py and which causes the error.

e.g. Do not give your python source code following names etc.:

  1. random.py
  2. time.py
  3. csv.py
  4. etc... ... ... ....
Sign up to request clarification or add additional context in comments.

6 Comments

files with same name as that of the modules imported can cause such errors
Please see the following URL: stackoverflow.com/questions/4761138/…
When you're importing random, you're actually importing your own python file, rather than the random module, so this answer is correct.
Okay, I got it. If you have a .py with the same name as a module, python calls it before the original
in this instance, probably, as it is named the same as the library he/she is trying to import. afaik when encountering an import statement, python looks first in the current directory and then in the library paths, as his/her file is called random.py python will (quite happily) import it
|
0

You can try re-naming the file and try again

Comments

0

Never name your files as random.py.

Comments

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.