Why is this python program not working?

I started learning python. I wrote a very simple program.

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

I run this from the command line.

 python random.py 

He returned with an 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' 

This is a very simple program, I can’t understand what mistake I made in this. Can someone help me with this? Thanks in advance. (operating system: Windows 7, python version: 2.7)

+7
source share
4 answers

Do not random.py your file random.py , it imports itself and searches for uniform .

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

+24
source

Do not name your program as a library. And just like a hint: you don’t need a line that stores and prints something right after it is created.

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

This works fine too;)

+4
source

Your problem is that you called your test program "random.py". The current working directory is in the first place to find the module, so when you say "import random", it imports your own test program, not the standard library.

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

+2
source

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

However, I highly recommend that you take the Python Tutorial before trying any other tutorial or book. You especially need to learn more about Python areas and spaces .

+1
source

All Articles