Why this python program is not working? AttributeE

2019-01-19 15:51发布

I wrote a very simple python program.

#!/usr/bin/env python
import random
x = random.uniform(-1, 1)
print str(x)

I run this from command prompt.

python random.py

It returned with error:

Traceback (most recent call last):
  File "random.py", line 2, in <module>
    import random
  File "D:\python practise\random.py", line 3, in <module>
    x = random.uniform(-1, 1)
AttributeError: 'module' object has no attribute 'uniform'

It is a very simple program, I can't understand what mistake I did in this.

(operating system: Windows 7; python version: 2.7)

标签: python random
4条回答
叼着烟拽天下
2楼-- · 2019-01-19 16:28

Your problem is that you named your test program "random.py". The current working directory is on the module search path before anything else, so when you say "import random", it imports your own test program rather than the standard library random.

Rename your test program -- or just take the .py suffix off -- and it should work.

查看更多
闹够了就滚
3楼-- · 2019-01-19 16:30

Don't name your program as an Library. And just as a Tip: You don't need an String storing something and printing it out just after generating it.

#!/usr/bin/env python
import random
print(random.uniform(-1, 1))

This will work fine too ;)

查看更多
倾城 Initia
4楼-- · 2019-01-19 16:41

Don't name your file random.py, it is importing itself and looking for uniform in it.

It's a bit of a quirk with how Python imports things, it looks in the local directory first and then starts searching the PYTHONPATH. Basically, be careful naming any of your .py files the same as one of the standard library modules.

查看更多
三岁会撩人
5楼-- · 2019-01-19 16:42

The solution to your problem is renaming your file (random.py) to something other than Python built-ins, standard libraries, reserved keywords etc.

However I strongly recommend you take Python Tutorial, before trying any other tutorial or book. You especially need to learn more about Python scopes and namespaces.

查看更多
登录 后发表回答