Python "import random" Error - python

As you may know from my previous posts, I'm learning Python. And this time I have a small error which I think is with this build of Python itself. When using the following:
import random
number = random.randint(1,10000)
Python gives me this error:
File "C\Users\name\Documents\Python\random.py", line 5, in (module)
print random.random()
TypeError: 'module' object is not callable
Every time I try to run it. Me no understand. Any help would be much appreciated!
EDIT: The two lines of code I'm trying to run:
import random
print random.randint(1,100)
That's it. And it gives me the same error.

By naming your script random.py, you've created a naming conflict with the random standard library module.
When you try to run your script, the directory containing the script will be added to the start of the module import path. So when your script does import random, you're effectively running a second copy of the script as the random module.
When the random module runs import random, it means that random.random will also be a reference to your module. So when you attempt to call the random.random() standard library function, you're actually attempting to call the module object resulting in the error you got.
If you rename your script to something else, the problem should go away.

Even I faced the same problem. I have renamed my python file from random.py to shuffle.py. This didn't work out. Then I changed the version then it worked. This may help a bit.
Python version : 3.6.7
replace
import random;
to
import random2;

I am using pycharm and I had to take the additional step to import the methods from random. In my case:
import random
from random import choice

The simple answer: Change your filename from "random.py" to something else as it is conflicting with random library.

Related

Python Module not found error - not getting fixed

So I am pretty new with Python. I've been working on running with a code similar to one I hope to build myself (so a reference code). Aside from some bugs I need to work out with invalid syntax, all seems to work except for one issue with one particular .py file I have.
My structure is this:
MoodForecasting -> eval -> nsga_two.py
I do have _init_.py in eval folder though, so I'm not sure why this block of code isn't working.
I am trying to load one particular fucntion from it, so the structure should look like this
from nsga_two import PatientProblem
Unfortunately, I keep getting the error ModuleNotFoundError: No module named 'nsga_two'.
I checked nsga_two.py itself and found that it couldn't load inspyred. I went in and was able to fix this. So, nsga_two.py runs fine on its own. However, I cannot import it into the main script I will be working with.
Some extra details: I am working with the IDE Spyder with Python Custom Version 3.7.9.
I'm not sure if it is an issue with Spyder or just how I am loading in my working directory. (Most of my coding experience is in MatLab and R so having an IDE similar to RStudio and MatLab is the reason I chose to work in Spyder)
Edit:
I got a syntax error when using from eval import nsga_two.PatientProblem. Python didn't like the period. So, I instead tried it with no period. I got the error cannot import name 'nsga_twoPatientProblem' from 'eval' (C:\Users\name\Desktop\MoodForecasting-master\MoodForecasting-master\eval\__init__.py). I don't know why. But doing from eval import nsga_two works. nsga_two.py only consists of PatientProblem. This solve should be ok for this purpose. I'm just not sure why this could be happening.
Suppose your structure is like:
MoodForecasting-master/
main.py
eval/
__init__.py
nsga_two.py
When you run the main script to import something, the directory of that script is added to the module search path sys.path, .../MoodForecasting-master/ in this case. from nsga_two import PatientProblem raised ModuleNotFoundError because nsga_two.py is not in that directory.
As Iguananaut said, from eval import nsga_two.PatientProblem in the first comment has never been a valid statement. The valid ways of doing so are:
import by from eval import nsga_two and use as nsga_two.PatientProblem().
import by from eval.nsga_two import PatientProblem and use as PatientProblem() directly.
Module search starts from .../MoodForecasting-master/, first option go to .../MoodForecasting-master/eval/ to find nsga_two.py, second option go to .../MoodForecasting-master/eval/nsga.py to find attribute named PatientProblem.
The correct syntax would be:
from package.module import function
so:
from eval.nsga_two import PatientProblem

sagemath: How to find the right import library names for writing a python prog to load from sage

Newbie to SageMath. Tried out different things from the Console & it worked fine. Now I want to automate into Python Program.
The same function which I call from the sage console is giving a NameError: name '<xxxx>' is not defined. I am assuming I have to import some modules in my python program. But there doesn't seem to be an easy way to figure out which one to import.
For e.g. in Java, let's say I want to use HashMap, I just google HashMap java & the first hit I get is https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
Which clearly tells me that I have to import it from java.util.
I can't find something similar for sagemath.
Now this is the code I want to call from my sagemath python program
c = <somenumber>
n = <somenumber>
r = Modular(c, n).sqrt()
I obviously get the error
NameError: name 'Modular' is not defined
How do I find out what I have to import to fix this error?
I googled for sagemath Modular and went through a couple of pages of results & I couldn't find what I have to import in an easy way.
Obviously, my first priority here is to figure out what to import for calling Modular & sqrt but the bigger question is how to do this everytime.
How is this done by sagemath users?
I think you want Mod and not Modular.
To get the correct import statements, in a Sage session, try:
sage: import_statements(Mod)
which will suggest:
from sage.rings.finite_rings.integer_mod import Mod

how do i correctly import a package in python?

Hello everyone im currently learning python and i im having some problems importing modules and packages. Actually i think is more of a problem with vscode.
i have this package called "paquete" with a module (funciones) that i want to import to my "main" with some fuctions in it to test if it all works correctly but i still getting "emphasized items and unresolved-import" warnings.
but for some reason it works just fine.
is more of a annoying thing.
EDIT:
module with the function "funcion"
the warning that appears in the main folder "prueba" is "emphasized items"
i tried what u guys told me to do but it stills shows the warnings
As you are trying to import a specific function from module in python
You should use in this manner:
from paquete import funciones
If you want to import full module then use:
import paquete
I can't tell whats in the funciones file. But normally this yellow import lines are telling you that you import functions, which you dont use.
Try this instead if you only want
funcion
to be imported.
from paquete.funcions import funcion
This is also better because you import only the functions you need, not all of the functions you declared in the other file. Also all imports of the other file will be loaded into your file if you import with an asterix.
The issue is you are doing all of this from within a directory named prueba. If you changed the import to from prueba.paquete.funciones import * it should work after you add a __init__.py file to your prueba directory. The other option is to use a relative import: from .paquete.funciones import *.
But do note that using import * is strongly discouraged when you are not working within the REPL. It's much better to import to the module and then reference things off the module, e.g. from prueba.paquete import funciones, from .paquete import funciones, or import prueba.paquete.funciones. That way you know exactly where things in your code came from without having to read the top of your file.
pip3 intall "name"
Use Pycharm, rather than Vscode

Python - object has no attribute 'randint'

I want to import the random module to use randint and get a random number from 1 to 10. I have this so far:
import random
number = random.randint(1,10)
print number
I've also tried importing randint specifically, but that doesn't work either. With the code above, I get object has no attribute 'randint.'
I've come across plenty of people getting this error. The solution has always been to find the file you've named random.py and change its name because the script is loading that instead of the real module. I understand that, but I can't find that file; I've searched high and low, and the only file I can find named random.py is the real module in the Python library list.
I think you're probably using a statement too specific at the top of your file such as:
from random import random
Instead of the correct, (but more broad) statement:
import random
From what you're saying, you can import random, but it's not the random module.
If random.__file__ works, then it's another module, and you get the path. Remove this path from your python file, or rename the file.
If it does not work (as your comment suggests), you need to investigate further. Use type(random), help(random), etc... to find out what it is and you should be able to get more color. See if you are importing some modules before in your workflow, in which random is defined.
I have run into this basic issue multiple times. You would think I would learn by now.
You may have a file in that directory or in the path of your own making that is called "random.py"
When you go to import random from your code it steps on itself.
Add this (#!/usr/bin/python)to your top of the file save and run again.
#!/usr/bin/python
It will automatically add this two line below to above #!/usr/bin/python, (FYI I am using Sublimetext3)
(# -*- coding: utf-8 -*-)
from __future__ import unicode_literals

Python name 'os' is not defined even though it is explicitly imported

I have a module called imtools.py that contains the following function:
import os
def get_imlist(path):
return[os.path.join(path,f) for f in os.listdir(path) if f.endswith('.jpg')]
When I attempt to call the function get_imlist from the console using import imtools and imtools.get_imlist(path), I receive the following error:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\...\PycharmProjects\first\imtools.py", line 5, in get_imlist
NameError: name 'os' is not defined
I'm new at Python and I must be missing something simple here, but cannot figure this out. If I define the function at the console it works fine. The specific history of this module script is as follows: initially it was written without the import os statement, then after seeing the error above the import os statement was added to the script and it was re-saved. The same console session was used to run the script before and after saving.
Based on small hints, I'm going to guess that your code didn't originally have the import os line in it but you corrected this in the source and re-imported the file.
The problem is that Python caches modules. If you import more than once, each time you get back the same module - it isn't re-read. The mistake you had when you did the first import will persist.
To re-import the imtools.py file after editing, you must use reload(imtools).
Same problem is with me I am also trying to follow the book of Programming Computer Vision with Python by Jan Erik Solem" [http://programmingcomputervision.com/]. I tried to explore on internet to see the problem but I did not find any valuable solution but I have solved this problem by my own effort.
First you just need to place the 'imtools.py' into the parent folder of where your Python is installed like C:\Python so place the file into that destination and type the following command:
from PIL import Image
from numpy import *
from imtools import *
Instead of typing the code with imtools.get_imlist() you just to remove the imtools from the code like:
get_imlist()
This may solve your problem as I had found my solution by the same technique I used.

Categories