What is the difference between random IMPORT * and IMPORT randomly? (random () and randrange ())

The code was given in this book:

from random import* for i in range(15): print random.randrange(3,13,3) 

And he has a result in the book.

But when I run it in Netbeans. The following reinforcements were canceled:

*

Traceback (last last call): File "C: \ Users \ Lacces \ Documents \ NetBeansProjects \ Python_GS_Tanuljunk_meg_programozni \ SRC \ Adatszerkezetek \ Lista.py", line 11, in print random.randrange (3,13,3) # 3-tól 13-ig, 3 érték elválasztásal AttributeError: object 'builtin_function_or_method' has no attribute 'randrange'

*

I have a call to help Google and I found this for import:

 import random 

With this, I used this instead of accidentally importing *

And it worked! No exception!

Can someone explain to me why the first time an exception is thrown, and why not the second time (for a novice programmer :))

+4
source share
4 answers

When you are from random import * , all definitions from random become part of the current namespace. This means that you do not need to attribute anything with random. , but it also means that you can get a name clash without even knowing it.

The preferred method is import random .

+7
source

Importing everything from a module is not recommended just because of these amazing side effects: the random module contains a random function, so import * from random does the following:

 from random import randrange from random import random ... 

Now, when you access random , you get access to the function instead of the module. You can use randrange (without the random. Prefix), but import random and explicitly indicating which module the function is from is the best idea.

+3
source

If you use "from moduleName import ....", you get all the classes, functions and variables that you specified after import, or everything if you specify * .: from random import * for I in range (15):
print randrange (3,13,3)

But note that it’s not very good to import everything, it would be better to import only the necessary classes, functions and variables, so if you only need a randrange that you need to use:

 from random import randrange for i in range(15): print randrange(3,13,3) 

If you use random import, it means that you are importing a module, so you need to specify moduleName. when you want to use it like this:

 import random for i in range(15): print random.randrange(3,13,3) 
+2
source

from random import * imports all functions from a module called random, but not random .

Here you can directly call functions randomly: randrange(3,13,3) , etc.

import random imports a import random name from which you can later call functions as follows: random.randrange(3,13,3) , etc.

+2
source

All Articles