r/learnpython • • 4d ago

Why wont this work?

The code works if IDLE python but when using visual studio code i keep getting "name 'randrange' is not defined" error anyone know why it doesn't work in visual studio?

from random import *
from turtle import *


forward(randrange(1, 10))


done()from random import *
from turtle import *


forward(randrange(1, 10))


done()
0 Upvotes

14 comments sorted by

6

u/atarivcs 4d ago

Do you have your own python file named random.py ?

1

u/hff22 4d ago

yes

8

u/Buttleston 4d ago

This might be why then - if random.py is in the same directory as your source code, it won't know you meant to import the python built in library named random, since "from foo import *" will also import from foo.py

2

u/hff22 4d ago

omg that was it thank you very much

1

u/Cybyss 4d ago

I once built a parser generator in Python, where one of my code files was named token.py.

The errors I got from that sure took some time to debug.

4

u/atarivcs 4d ago

Then that is the reason.

The import statement looks in the current directory first, so it finds your local module random.py instead of the real system module by that name.

Rename your module to something else.

2

u/lfdfq 4d ago

'Using' visual studio code, in what way? Is the message you see coming from running Python on the file? or something VS Code is showing you? or something else?

It's very hard to help, since the code works (you say so yourself). Maybe you aren't running the code you think, or did not save the file correctly, or are looking at the wrong file, or any number of other unrelated problems.

1

u/hff22 4d ago

Visual studio shows me the error I stated above and im using the VS code python extension turtle works just fine but it just won't work with randrange

3

u/zanfar 4d ago

Don't use star imports. They don't import everything, which is probably your issue here.

Also, don't name files in your working directory the same as standard library packages.

1

u/HummingHamster 4d ago

Try explicit import, there might be issue with VS's in supporting wildcard import.