In the book has been this codesample:
from random import*
for i in range(15):
print random.randrange(3,13,3)
And it have got result in the book.
But when I run it in the Netbeans. The following excaption arosed:
*
Traceback (most recent call last): 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: 'builtin_function_or_method' object has no attribute 'randrange'
*
I have call to help the google, and I found this for the import:
import random
With that I used this instead of from random import*
And it worked! No exception!
Can somebody explain to me why throw exception at the first time, and why not at the second time (for a beginner programmer:))
When you from random import *, all the definitions from random become part of the current name space. This means you don't have to prefix anything with random., but it also means you may get a name collision without even knowing it.
The preferred way is import random.
Importing everything from a module is discouraged just because of these surprising side effects: The module random contains a function random, so import * from random does the following:
from random import randrange
from random import random
...
Now, when you're accessing random, you're accessing the function instead of the module. You could use randrange (without the prefix random.), but import random and explicitly stating what module a function is from is the better idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With